All about JavaScriptExecutor in Selenium

As per the selenium official link on Selenium RC, core selenium is basically a javascript program (set of functions) which interprets and executes selenium commands using browser's built in javascript interpreter.

Sometimes we observe web controls doesn't react well to selenium commands, there we can directly use / execute javascript commands using webdriver,


To execute javascript using selenium, we have JavascriptExecutor interface.
     WebDriver driver;
     driver = new FirefoxDriver();
     JavascriptExecutor js = (JavascriptExecutor) driver;
Note: Almost we can execute any javascript commands in selenium, but not the javaScript functions.

Refer below, for how to identify HTML elements by executing JavaScript in selenium
How to Identify an element (javaScript locators) 
and
How to handle browser element actions

Let's see some more detail of how we can
Below code example shows:
How to create an alert and to get page title using selenium/javaScript
public class Test1 {
 public static void main(String[] args) {
  WebDriver driver;
  driver = new FirefoxDriver();
  driver.get("http://www.qavalidation.com/p/demo.html");
  
  JavascriptExecutor js = (JavascriptExecutor) driver;
  
  //pop up an alert with msg
  js.executeScript("alert('Hello QAV');");
  
  String AlertTxt = driver.switchTo().alert().getText();
  System.out.println("Alert txt:"+ AlertTxt);
  driver.switchTo().alert().accept(); //bypass alert

  //selenium command
  //String pageTitle = driver.getTitle(); 
  String pageTitle = (String) js.executeScript("return document.title");
  //JS command
  System.out.println("PageTitle:" + pageTitle); 
 }
}

So in above program, we created a driver instance and casting to javascriptexecutor instance
(we can create an instance JavascriptExecutor interface, as FirefoxDriver implements JavascriptExecutor interface), then write commands / statments as parameters for the executescript method.

let's see some more implementations on using javaScript in selenium:
  • Load URL on browser
js.executeScript("window.location = 'http://www.qavalidation.com/p/demo.html'");
  • To know if the page load done or not:
String status = js.executeScript("return document.readyState").toString();
System.out.println("Page loaded?" + status);
  • Highlight an element on browser:
//Highlight an element
js.executeScript("document.getElementById('username').style.borderColor = 'Red'");
  • How to get the current URL
String CurrentURL = js.executeScript("return document.URL").toString();
System.out.println("Current URL: " + CurrentURL);
  • Get the domain name
String DomainName= js.executeScript("return document.domain").toString();
System.out.println("Domain Name: " + DomainName);


2 comments: