JavascriptExecutor in Selenium WebDriver

Reading Time: 4 minutes

JavascriptExecutor 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. There are scenarios where the actual Webdriver commands will not work efficiently as expected and this is where JavaScriptExecutor comes into the picture. As JavaScriptExecutor is a Selenium interface therefore there is no need for an extra plugin or add-on. You can use it directly by importing the package org.openqa.selenium.JavascriptExecutor.

Why use JavascriptExecutor in Selenium?

There are various locators used in selenium webDriver such as ID, classname, CSS Selectors, Xpath etc. Sometimes these default Selenium locators may not work and there comes the JavaScriptExecutor in the picture. JavaScript is a programming language that interacts with HTML in a browser, and to use this function in Selenium, JavascriptExecutor is required. JavaScriptExecutor is used to perform operations on a web page.

Sometimes Selenium gives incorrect results due to unexpected actions that occur while running a script. Suppose 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 , We use click() method for clicking any element on webpage. Sometimes web controls don’t react well against Selenium commands and we may face issues with the click() method. 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 following packages for using Java Script Executor.

Package
import org.openqa.selenium.JavascriptExecutor;
Syntax
//To utilize JavascriptExecutor, create a reference for the interface and assign it to the WebDriver instance by type casting it.

JavascriptExecutor js = (JavascriptExecutor) driver;

//We have created a JavascriptExecutor reference and now we call the executeAsyncScript/executeScript methods. The syntax for executeScript is given below:
 
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.

The script can return values. Data types returned are.

  • Boolean
  • Long
  • String
  • List
  • WebElement.

Introduction to JavaScriptExecutor Methods

JavaScriptExecutor in Selenium provides two methods through which we can run JavaScript on the selected window or the current page.

  1. executeScript

This method executes JavaScript in the context of the currently selected window or frame in Selenium and the script will be executed as the body of an anonymous function.

2. executeAsyncScript

This method executes an asynchronous snippet of JavaScript in the context of the currently selected window or frame in Selenium nd here also, the script will be executed as the body of an anonymous function. The major difference between executeScript and executeAsyncScript is that the script invoked using the executeAsyncScript has to signal about the completion of execution using the callback function but thats not the case in executeScript.

Some Scenarios Where You Can Use JavaScriptExecutor in Selenium

1. To Click on a Button

js.executeScript("document.getElementById('enter element id').click();");

//or

js.executeScript("arguments[0].click();", cancelButton);

2. To Handle Checkbox by passing the value as true or false

js.executeScript("document.getElementById('enter element id').checked=false;");

3. To Type Text in a Text Box without using sendKeys() method

js.executeScript("document.getElementById('some id').value='someValue';");
js.executeScript("document.getElementById('Email').value='Knoldus.com';");

4. To generate Alert Pop window in Selenium Webdriver

js.executeScript("alert('Welcome To Knoldus');");

5. To refresh browser window using Javascript

js.executeScript("history.go(0)");

6. To get the innertext of the entire webpage in Selenium

String innerText = js.executeScript(" return document.documentElement.innerText;").toString();
System.out.println(innerText);

7. To get the Title of our webpage

String titleText =  js.executeScript("return document.title;").toString();
System.out.println(titleText);

8. To get the URL of a webpage

String url=  js.executeScript("return document.URL;").toString();
System.out.println(url);

9. To navigate to a different page using Javascript

js.executeScript("window.location = 'https://www.knoldus.com");

10. To get the domain name

String domainName=  js.executeScript("return document.domain;").toString();
System.out.println(domainName);

11. To find a hidden element in selenium using JavaScriptExecutor

js.executeScript("arguments[0].click();", element);

12. To perform Scroll on an application using Selenium


//Vertical scroll - down by 800  pixels
js.executeScript("window.scrollBy(0,800)");

// for scrolling till the bottom of the page we can use the code like
js.executeScript("window.scrollBy(0,document.body.scrollHeight)");
Practical Example of executeScript using Selenium JavaScriptExecutor
package knoldusTestingMaterial;

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 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='knoldus.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 100  pixels
		js.executeScript("window.scrollBy(0,100)");
		// for scrolling till the bottom of the page we can use the code like
		//js.executeScript("window.scrollBy(0,document.body.scrollHeight)");*/
		
		/*//to navigate to different page using Javascript?
	        //Navigate to new Page
	        js.executeScript("window.location = 'https://www.softwaretestingmaterial.com");*/
	}
}
Practical Example using executeAsyncScript
package knoldusTestingMaterial;

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 JavaScriptExecutorClass {
@Test 
public void Login() 
{ 
WebDriver driver= new FirefoxDriver(); 
JavascriptExecutor js = (JavascriptExecutor)driver;
 
//To launch a site 
driver.get("https://www.knoldus.com"); 

//To maximize the window 
driver.manage().window().maximize(); 

//To set the script timeout to 15 seconds 
driver.manage().timeouts().setScriptTimeout(15, 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(argumentsarguments.length - 1], 10000);"); 

//To get the difference current time and start time 
System.out.println("Wait time: " + (System.currentTimeMillis() - startTime)); 
}
}

That’s all for this blog . Hope you have enjoyed it . For more such blogs please visit Knoldus Blogs section. Happy Learning! Happy Testing!

Written by 

Saumya is a Software Consultant at Knoldus Software LLP. She has done B.Tech from Quantum School of Technology, Roorkee. She has good knowledge of Devops technologies like Ansible, Terraform, Docker, Concourse, Jenkins, Kubernetes. She is very enthusiastic and energetic. Apart from technology, she is interested in various sports.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading