How to use JavaScript with Selenium WebDriver Java

JavaJavascriptSelenium Webdriver

Java Problem Overview


I want to use JavaScript with WebDriver (Selenium 2) using Java.

I've followed some a guide and on Getting Started page: there is an instruction at 1st line to run as:

$ ./go webdriverjs

My question: From which folder/location the command mentioned above will be run/executed?

Java Solutions


Solution 1 - Java

Based on your previous questions, I suppose you want to run JavaScript snippets from Java's WebDriver. Please correct me if I'm wrong.

The WebDriverJs is actually "just" another WebDriver language binding (you can write your tests in Java, C#, Ruby, Python, JS and possibly even more languages as of now). This one, particularly, is JavaScript, and allows you therefore to write tests in JavaScript.

If you want to run JavaScript code in Java WebDriver, do this instead:

WebDriver driver = new AnyDriverYouWant();
if (driver instanceof JavascriptExecutor) {
    ((JavascriptExecutor)driver).executeScript("yourScript();");
} else {
    throw new IllegalStateException("This driver does not support JavaScript!");
}

I like to do this, also:

WebDriver driver = new AnyDriverYouWant();
JavascriptExecutor js;
if (driver instanceof JavascriptExecutor) {
    js = (JavascriptExecutor)driver;
} // else throw...

// later on...
js.executeScript("return document.getElementById('someId');");

You can find more documentation on this here, in the documenation, or, preferably, in the JavaDocs of JavascriptExecutor.

The executeScript() takes function calls and raw JS, too. You can return a value from it and you can pass lots of complicated arguments to it, some random examples:

    // returns the right WebElement
    // it's the same as driver.findElement(By.id("someId"))
    js.executeScript("return document.getElementById('someId');");

2.

    // draws a border around WebElement
    WebElement element = driver.findElement(By.anything("tada"));
    js.executeScript("arguments[0].style.border='3px solid red'", element);

3.

    // changes all input elements on the page to radio buttons
    js.executeScript(
            "var inputs = document.getElementsByTagName('input');" +
            "for(var i = 0; i < inputs.length; i++) { " +
            "    inputs[i].type = 'radio';" +
            "}" );

Solution 2 - Java

JavaScript With Selenium WebDriver

Selenium is one of the most popular automated testing suites. Selenium is designed in a way to support and encourage automation testing of functional aspects of web based applications and a wide range of browsers and platforms.

	public static WebDriver driver;
	public static void main(String[] args) {
		driver = new FirefoxDriver(); // This opens a window	
		String url = "----";
		
		
		/*driver.findElement(By.id("username")).sendKeys("yashwanth.m");
		driver.findElement(By.name("j_password")).sendKeys("yashwanth@123");*/
		
		JavascriptExecutor jse = (JavascriptExecutor) driver;		
		if (jse instanceof WebDriver) {
			//Launching the browser application
	     	jse.executeScript("window.location = \'"+url+"\'");
jse.executeScript("document.getElementById('username').value = \"yash\";");
// Tag having name then
driver.findElement(By.xpath(".//input[@name='j_password']")).sendKeys("admin");

			
//Opend Site and click on some links. then you can apply go(-1)--> back  forword(-1)--> front.
//Refresheing the web-site. driver.navigate().refresh();			
jse.executeScript("window.history.go(0)");
			jse.executeScript("window.history.go(-2)");
			jse.executeScript("window.history.forward(-2)");

			String title = (String)jse.executeScript("return document.title");
			System.out.println(" Title Of site : "+title);
			
			String domain = (String)jse.executeScript("return document.domain");
			System.out.println("Web Site Domain-Name : "+domain);
			
			// To get all NodeList[1052] document.querySelectorAll('*');  or document.all
			jse.executeAsyncScript("document.getElementsByTagName('*')");
			
			String error=(String) jse.executeScript("return window.jsErrors");
			System.out.println("Windowerrors  :   "+error);
			
			
			
			System.out.println("To Find the input tag position from top"); 
			ArrayList<?> al =  (ArrayList<?>) jse.executeScript(
					"var source = [];"+
					"var inputs = document.getElementsByTagName('input');"+
					"for(var i = 0; i < inputs.length; i++) { " +
				       "   source[i] = inputs[i].offsetParent.offsetTop" +      //"    inputs[i].type = 'radio';"
				    "}"+
				    "return source"				   	
					);//inputs[i].offsetParent.offsetTop     inputs[i].type
			
			System.out.println("next");
			System.out.println("array : "+al);
			
			// (CTRL + a) to access keyboard keys. org.openqa.selenium.Keys 
			Keys k = null;
			String selectAll = Keys.chord(Keys.CONTROL, "a");
			WebElement body = driver.findElement(By.tagName("body"));
			body.sendKeys(selectAll);
			
			// Search for text in Site. Gets all ViewSource content and checks their.
			if (driver.getPageSource().contains("login")) {
				System.out.println("Text present in Web Site");
			}
		
		Long clent_height = (Long) jse.executeScript("return document.body.clientHeight");
		System.out.println("Client Body Height : "+clent_height);
		
		// using selenium we con only execute script but not JS-functions.
		
	}
	driver.quit(); // to close browser
}

To Execute User-Functions, Writing JS in to a file and reading as String and executing it to easily use.

Scanner sc = new Scanner(new FileInputStream(new File("JsFile.txt")));
		String js_TxtFile = "";	
			while (sc.hasNext()) {			
				String[] s = sc.next().split("\r\n");	
				for (int i = 0; i < s.length; i++) {
					js_TxtFile += s[i];
					js_TxtFile += " ";
				}			
			}
		String title =  (String) jse.executeScript(js_TxtFile);
		System.out.println("Title  : "+title);

document.title & document.getElementById() is a property/method available in Browsers.

JsFile.txt

var title = getTitle();
return title;

function getTitle() {
	return document.title;
}

Solution 3 - Java

You can also try clicking by JavaScript:

WebElement button = driver.findElement(By.id("someid"));
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].click();", button);

Also you can use jquery. In worst cases, for stubborn pages it may be necessary to do clicks by custom EXE application. But try the obvious solutions first.

Solution 4 - Java

I didn't see how to add parameters to the method call, it took me a while to find it, so I add it here. How to pass parameters in (to the javascript function), use "arguments[0]" as the parameter place and then set the parameter as input parameter in the executeScript function.

    driver.executeScript("function(arguments[0]);","parameter to send in");

Solution 5 - Java

If you want to read text of any element using javascript executor, you can do something like following code:

WebElement ele = driver.findElement(By.xpath("//div[@class='infaCompositeViewTitle']"));
String assets = (String) js.executeScript("return arguments[0].getElementsByTagName('span')[1].textContent;", ele);

In this example, I have following HTML fragment and I am reading "156".

<div class="infaCompositeViewTitle">
   <span>All Assets</span>
   <span>156</span>
</div>

Solution 6 - Java

Following code worked for me:

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.springframework.beans.factory.annotation.Autowired;

public class SomeClass {

    @Autowired
    private WebDriver driver;

     public void LogInSuperAdmin() {
        ((JavascriptExecutor) driver).executeScript("console.log('Test test');");
     }
}

Solution 7 - Java

I had a similar situation and solved it like this:

WebElement webElement = driver.findElement(By.xpath(""));
webElement.sendKeys(Keys.TAB);
webElement.sendKeys(Keys.ENTER);

Solution 8 - Java

You need to run this command in the top-level directory of a Selenium SVN repository checkout.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRipon Al WasimView Question on Stackoverflow
Solution 1 - JavaPetr JanečekView Answer on Stackoverflow
Solution 2 - JavaYashView Answer on Stackoverflow
Solution 3 - JavaLukaszView Answer on Stackoverflow
Solution 4 - JavaDavid MarcielView Answer on Stackoverflow
Solution 5 - JavamuhdchoaibView Answer on Stackoverflow
Solution 6 - JavaHabib MammadovView Answer on Stackoverflow
Solution 7 - JavaNicolas R Vivas LopezView Answer on Stackoverflow
Solution 8 - JavaDaniel WagnerView Answer on Stackoverflow