JavaScriptExecutor in Selenium WebDriver, Methods with Examples
In this Selenium JavaScriptExecutor tutorial, we will learn the following
What is JavaScript?
JavaScript is a programming language to interact with HTML DOM within the browser.
What is JavaScriptExecutor?
JavaScript executor is an interface provided by Selenium that gives a mechanism to execute JavaScript through Selenium WebDriver.
It provides two methods such as “executeScript” & “executeAsyncScript” to run JavaScript on the currently selected frame or window or page.
Why we use JavaScriptExecutor?
There are locators in Selenium WebDriver like ID, Class, XPath, etc., to work with elements on a web page.
Sometimes these default Selenium locators may not work. Here comes the JavaScriptExecutor in the picture.
JavaScriptExecutor is used to perform operations on a web page.
To use JavaScriptExecutor in Selenium scripts there is no need to install an addon or plugin.
The only step we need to take is to import org.openqa.selenium.JavascriptExecutor in the Selenium script.
JavascriptExecutor in Selenium enables the WebDriver to interact with HTML DOM within the browser.
Sometimes Selenium gives incorrect results due to unexpected actions that occur while running a script. Say there is a popup when we open a website. Due to this Selenium cannot find the specific element which we recorded in the script and it throws an error or incorrect result.
For example:
In general, we do click on an element using the click() method in Selenium.
driver.findElement(By.id("Id Value")).click();
Sometimes web controls don’t react well against Selenium commands and we may face issues with the above statement “click()“. As said earlier, to overcome such kind of situation, we use the JavaScriptExecutor interface.
There is no need to write a separate script to execute JavaScript within the browser using the Selenium WebDriver script. Just use a predefined interface named ‘Java Script Executor‘.
We need to import the below package in the script.
Package:
import org.openqa.selenium.JavascriptExecutor;
Syntax:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(Script,Arguments);
Script – The JavaScript to execute
Arguments – The arguments to the script(Optional). May be empty.
Returns – One of Boolean, Long, List, String, List, Boolean, WebElement, or null.
Methods in JavaScriptExecutor
JavaScriptExecutor methods are as follows
- executeAsyncScript
- executeScript
#1. executeAsyncScript
This method executes an asynchronous piece of JavaScript in the context of the currently selected window or frame in Selenium. Asynchronous script renders your webpage fastly.
#2. executeScript
This method executes JavaScript in the context of the currently selected window or frame in Selenium.
The script which we used in this method executes in the body of an anonymous function. We can pass complicated arguments to it.
- Long
- List
- String
- Boolean
- WebElement
How We Use JavaScriptExecutor in Selenium
Let’s see some scenarios we could handle using JavaScriptExecutor Interface:
Scenario #1: To Type Text in a Text Box
To type Text in Selenium WebDriver without using sendKeys() method
js.executeScript("document.getElementById('some id').value='someValue';");
js.executeScript("document.getElementById('Email').value='SoftwareTestingMaterial.com';");
Scenario #2: To Click on a Button
To click a Button in Selenium WebDriver using JavaScript
js.executeScript("document.getElementById('enter your element id').click();");
//or
js.executeScript("arguments[0].click();", loginButton);
Scenario #3: To Handle Checkbox
We pass true or false to handle the checkbox
js.executeScript("document.getElementById('enter element id').checked=false;");
Scenario #4: To generate Alert Pop window in selenium
js.executeScript("alert('Welcome To SoftwareTestingMaterial');");
Scenario #5: To refresh browser window using Javascript
js.executeScript("history.go(0)");
Scenario #6: To get innertext of the entire webpage in Selenium
String sText = js.executeScript("return document.documentElement.innerText;").toString();
System.out.println(sText);
Scenario #7: To get the Title of our webpage
String sText = js.executeScript("return document.title;").toString();
System.out.println(sText);
Scenario #8: To get the domain
String sText = js.executeScript("return document.domain;").toString();
System.out.println(sText);
Scenario #9: To get the URL of a webpage
String sText = js.executeScript("return document.URL;").toString();
System.out.println(sText);
Scenario #10: To perform Scroll on an application using Selenium
See Also: How To Scroll Web Page Down Or UP Using Selenium WebDriver
//Vertical scroll - down by 500 pixels
js.executeScript("window.scrollBy(0,500)");
// for scrolling till the bottom of the page we can use the code like
//js.executeScript("window.scrollBy(0,document.body.scrollHeight)");
Scenario #11: To click on a SubMenu which is only visible on mouse hover on Menu
js.executeScript("$('ul.menus.menu-secondary.sf-js-enabled.sub-menu li').hover()");
Scenario #12: To navigate to a different page using Javascript
js.executeScript("window.location = 'https://www.softwaretestingmaterial.com");
Scenario #13: To find a hidden element in selenium using JavaScriptExecutor
js.executeScript("arguments[0].click();", element);
#1. Practical Example of executeScript using Selenium JavaScriptExecutor
The below program will guide you to handle some of the scenarios we do use while writing scripts.
package softwareTestingMaterial;
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;
import org.testng.annotations.Test;
public class JavaScriptExecutorClassDummy {
static WebDriver driver;
@Test
public static void javaScriptExeMethod(){
System.setProperty("webdriver.gecko.driver","D://Selenium Environment//Drivers//geckodriver.exe");
driver = new FirefoxDriver();
driver.get("https://www.gmail.com");
WebElement loginButton = driver.findElement(By.xpath("//*[@id='next']"));
/*Syntax:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(Script,Arguments);
script - The JavaScript to execute
Arguments - The arguments to the script.(Optional)*/
JavascriptExecutor js = (JavascriptExecutor)driver;
//Uncomment each scenario by using Ctrl + Shift + \ (backslash) and find the solution
*//to type text in Selenium WebDriver without using sendKeys() method
js.executeScript("document.getElementById('some id').value='someValue';");
js.executeScript("document.getElementById('Email').value='SoftwareTestingMaterial.com';");*/
/*//to click a button in Selenium WebDriver using JavaScript
//js.executeScript("arguments[0].click();", loginButton);
//or
js.executeScript("document.getElementById('enter your element id').click();");
js.executeScript("document.getElementById('next').click();");*/
/*//to handle checkbox
js.executeScript("document.getElementById('enter element id').checked=false;");*/
/*//to generate Alert Pop window in selenium
js.executeScript("alert('hello world');");*/
/*//to refresh browser window using Javascript
js.executeScript("history.go(0)");*/
/*// to get innertext of the entire webpage in Selenium
String sText = js.executeScript("return document.documentElement.innerText;").toString();
System.out.println(sText);*/
/*//to get the Title of our webpage
String sText = js.executeScript("return document.title;").toString();
System.out.println(sText);*/
/*//to get the domain
String sText = js.executeScript("return document.domain;").toString();
System.out.println(sText);*/
/*//to get the URL of our webpage
String sText = js.executeScript("return document.URL;").toString();
System.out.println(sText);*/
/*//to perform Scroll on application using Selenium
//Vertical scroll - down by 50 pixels
js.executeScript("window.scrollBy(0,50)");
// for scrolling till the bottom of the page we can use the code like
//js.executeScript("window.scrollBy(0,document.body.scrollHeight)");*/
/* // to click on a SubMenu which is only visible on mouse hover on Menu?
//Hover on Automation Menu on the MenuBar
js.executeScript("$('ul.menus.menu-secondary.sf-js-enabled.sub-menu li').hover()");*/
/*//to navigate to different page using Javascript?
//Navigate to new Page
js.executeScript("window.location = 'https://www.softwaretestingmaterial.com");*/
}
}
#2. Practical Example using executeAsyncScript
executeAsyncScript renders your webpage faster. Using executeAsyncScript, our script runs by the browser side and not by the server side because it sends a callback to the server side testing suite once the script is ready.
package softwareTestingMaterial;
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; import org.testng.annotations.Test; public class JavaScriptExecutorClassDummy {
@Test
public void Login()
{
WebDriver driver= new FirefoxDriver();
JavascriptExecutor js = (JavascriptExecutor)driver;
//To launch a site
driver.get("https://www.softwaretestingmaterial.com");
//To maximize the window
driver.manage().window().maximize();
//To set the script timeout to 10 seconds
driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS);
//To declare and set the start time
long startTime = System.currentTimeMillis();
//Calling executeAsyncScript() method to wait for 10 seconds
js.executeAsyncScript("window.setTimeout(arguments[arguments.length - 1], 10000);");
//To get the difference current time and start time
System.out.println("Wait time: " + (System.currentTimeMillis() - startTime));
}
}
Don’t miss: What’s new in Selenium 4
Conclusion:
Learning how to handle JavaScriptExecutor in Selenium is mandatory to overcome the issues Selenium WebDriver faces sometimes while interacting with web elements.