How to use JavaScriptExecutor in selenium WebDriver?

In this article i will talk about how to use JavaScriptExecutor in Selenium WebDriver.

Suggested post to read:

 What is JavaScriptExecutor in selenium WebDriver?

Let us understand first what is JavaScriptExecutr. It is an interface which is used to execute JavaScript in selenium Webdriver code.

Selenium WebDriver uses pre-defined locators like id, class, Xpath, name, link etc. to locate the elements on webpage. So, in some cases, it becomes difficult to locate element or sometimes you may face consistency problem in locating element due to webpage code.

Many Situations occur in your project where code written with selenium – java (any language binding) does not work (at all or effectively).

There would be few tricky scenarios where just Webdriver object is not sufficient enough or optimum enough to handle with java for e.g. in few of my applications, the web page rendered is very long, and while doing operations with elements, I got errors. So, I used JavaScript in my script to handle the case. Some other cases where JavaScript comes handy is handling pop ups and alerts.

In another case, dropdown wasn’t working for me (it was not properly coded by using select class). It was selecting the elements with are currently visible, wasn’t searching in to the whole list. So, in this case, I need to keep scrolling down continuously & at the same time keep checking If the required option is available to select & is getting selected.

So, there are certain advantages involved when we use the two (java, JavaScript) judiciously in automation scripts. Both the languages are great in their own space.

What are the advantages of JavaScriptExecutr in Selenium?

1.      JavaScript is very efficient & accurate, as compare to the scripts written with Selenium-Java
2.     JavaScript executor allows you to run pure JavaScript code irrespective of the Selenium language binding (Java, C#, Python etc.) you are using.
3.     By using JavaScript, you can directly interact and /or alter elements on the page, more or less, like the page developer has done.
4.     JavaScript being a language which works very well with HTML offers innumerous workarounds/hacks on the page.
5.     JavaScript is recommended to use when Selenium – Java code tends to break for certain scenario, where JavaScript works perfectly.
6.     JavaScript is quite easy to pick up with the least amount of setup required. No special setup is required while using it with selenium
How to use JavaScriptExecutr (JavaScriptExecutr Syntax) –
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(Script,Arguments);
Where –
script – The JavaScript to execute
Arguments – The arguments to the script. (Optional)
Let us see few of the uses where we can use javaScripts in selenium WebDriver code.
       1.       To refresh browser
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript(“history.go(0)”);
       2.       To get Webpage title
JavascriptExecutor js = (JavascriptExecutor)driver;
String sText =  js.executeScript(“return document.title;”).toString();
        3.       To click on the button
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", element);
      where, element is the button webElement where you wanted to click.
         4.       To Scroll down the webpage
  JavascriptExecutor js = (JavascriptExecutor)driver;
  js.executeScript("window.scrollBy(0,50)");
-> This is to scroll 50 pixels down.
If you want to scroll down till the end of webpage, then –
  js.executeScript("window.scrollBy(0,document.body.scrollHeight)");
        5.       To navigate to webpage –
JavascriptExecutr js = (JavascriptExecutr)driver;
js.executeScript("window.location = ‘URL-TO-BE-NAVIGATED’");

          6.       To enter text in textbox using JavaScript
           JavascriptExecutr js = (JavascriptExecutr)driver; 
           js.executeScript(“document.getElementById(‘lst-ib’).value = ‘Text to be searched’;”);
Example of JavaScriptExecutor –
package basicsOfSelenium;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class JavaScriptExample {

 public static void main(String[] args) {
  
  WebDriver driver = new FirefoxDriver();

  //Navigate to google.com using javascript
  JavascriptExecutor js = (JavascriptExecutor)driver;
  js.executeScript("window.location = 'https://www.google.co.in'");
 
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  
  //Enter the text in textbox using javascript
  js.executeScript("document.getElementById('lst-ib').value = 'Text to be searched';");
  
  //Click on the button using javascript
  WebElement element  = driver.findElement(By.xpath("//*[@id='tsf']/div[2]/div[3]/center/input[1]"));
  js.executeScript("arguments[0].click();", element);

  //Get page Title using JavaScript
  String PageTitle =  js.executeScript("return document.title;").toString();
  System.out.println("Page title is: "+PageTitle);
  
  //To Refresh the browser using JavaScript
  js.executeScript("history.go(0)");
  
  //To Scroll Down the webpage 
    js.executeScript("window.scrollBy(0,50)");
    
    //to Scroll the webpage to bottom of page
    js.executeScript("window.scrollBy(0,document.body.scrollHeight)");
 }

}

Hope this example helps little bit to understand how to use JavaScript in selenium – java code.

Leave Comment

Your email address will not be published. Required fields are marked *

Looking for learning Framework Development from Scratch? Lookout for Detailed Framework Development videos on YouTube here -

https://www.youtube.com/automationtalks

Get the Framework code at Github Repo: https://github.com/prakashnarkhede?tab=repositories