Home » Enterprise Java » Selenium » Selenium Javascriptexecutor Tutorial

About Sarad Dhungel

Sarad Dhungel
I am a graduate in Computer Engineering from Howard University. Third place award winner in Intel-Cornell Cup. Passionate about new emerging software and technology. During free time, I enjoy reading about politics, business, spirituality, technology and traveling.

Selenium Javascriptexecutor Tutorial

1. Introduction

Java Script executor is an interface of Selenium WebDriver that has the functionality similar to that of Java Script and can interact with HTML DOM elements. Instead of using driver.findElement method of the Selenium WebDriver we can use JavaScriptExecutor Interface to perform similar action on the Page.

Want to master Selenium?

Subscribe to our newsletter and download the Selenium Programming Cookbook right now!

In order to get you prepared for your Selenium development needs, we have compiled numerous recipes to help you kick-start your projects. Besides reading them online you may download the eBook in PDF format!

 

It provides advantages over FindElement method while handling tricky XPath as well as finding element which are sometimes hidden. Not only that, we can perform several other Java Script actions such as Browser Object Model (BOM), AJAX in addition to HTML DOM actions with the help of JavaScript Executor.
Method available:

executeScript      It implements an asynchronous event of JS in current window or frame  
executeAsynScript  It implements JS in context of the selected frame or methods          

Reference: https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/JavascriptExecutor.html

2. Java Script Popup alert

Using executeScript of JavaScriptExecutor, we can send an alert on the webpage. In this code, once the page loads, a pop-up will be shown containing the message “hello java code geeks”. This is a TestNG Project with @BeforeTest, @Test and @AfterTest annotations. First, the block of @BeforeTest will run where the Firefox driver get instantiated and get() method will invoke the given URL. Then, @Test will run where, JavaScriptExecutor gets instantiated and executeScript() method will invoke the pop up alert. Finally, @AfterTest block will executed and browser will be closed.

package com.javacodegeeks.seleniumjavascriptexecutor;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class JSExecutor{
	
	public WebDriver driver;
	public String Url = "http://www.ebay.com";
	
	@BeforeTest
	public void setDriver()
	{
		driver = new FirefoxDriver();
		driver.get(Url);
	}
  @Test
  public void jspopUp()
  {
			
			JavascriptExecutor jse = ((JavascriptExecutor)driver);
		  	jse.executeScript("alert('hello Java Code Geeks');");
  }
  @AfterTest
  public void atEnd()
  {
	  driver.quit();
  }
}

pop up alert

Output

PASSED: jspopUp

===============================================
    Default test
    Tests run: 1, Failures: 0, Skips: 0
===============================================


===============================================
Default suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================

[TestNG] Time taken by [email protected]: 75 ms
[TestNG] Time taken by [email protected]: 70 ms
[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 1 ms
[TestNG] Time taken by [email protected]: 8 ms
[TestNG] Time taken by [email protected]: 4 ms
[TestNG] Time taken by [email protected]: 9 ms

3. Refreshing the browser

We can use JavaScript Executor to refresh a browser window. We can perform similar action using driver.navigate().refresh() with WebDriver. Similarly, in this code, once the url gets loaded, the page will refresh again with the JavaScript method jse.executeScript("history.go(0)"). This is also a TestNG Project with @BeforeTest, @Test and @AfterTest annotations. First, the block of @BeforeTest will run where the Firefox driver get instantiated and get() method will invoke the given URL. Then, @Test method will run where, JavaScriptExecutor gets instantiated and executeScript() method will invoke ("history.go(0)"). Finally, @AfterTest block will executed and browser will be closed.

package com.javacodegeeks.seleniumjavascriptexecutor;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class JSExecutor{
	
	public WebDriver driver;
	public String Url = "http://www.ebay.com";
	
	@BeforeTest
	public void setDriver()
	{
		driver = new FirefoxDriver();
		driver.get(Url);
	}
  @Test
  public void refresh()
  {
			
			JavascriptExecutor jse = ((JavascriptExecutor)driver);
			jse.executeScript("history.go(0)");
  }
  @AfterTest
  public void atEnd()
  {
	  driver.quit();
  }
}

Output

PASSED: refresh

===============================================
    Default test
    Tests run: 1, Failures: 0, Skips: 0
===============================================


===============================================
Default suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================

[TestNG] Time taken by [email protected]: 21 ms
[TestNG] Time taken by [email protected]: 37 ms
[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 1 ms
[TestNG] Time taken by [email protected]: 8 ms
[TestNG] Time taken by [email protected]: 3 ms
[TestNG] Time taken by [email protected]: 7 ms

4. Clicking a button

We can also use JavaScriptExecutor to click on any Web element on the page by passing using executeScript method and passing ("arguments[0].click(), element)

import java.util.concurrent.TimeUnit;
package com.javacodegeeks.seleniumjavascriptexecutor;
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.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class JSExecutor{
	
	public WebDriver driver;
	public String Url = "http://www.ebay.com";
	
	@BeforeTest
	public void setDriver()
	{
		driver = new FirefoxDriver();
		driver.get(Url);
	}
  @Test
  public void clickButton()
  {         driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
	        WebElement element = driver.findElement(By.xpath(".//*[@id='gh-ug']/a"));
			JavascriptExecutor jse = ((JavascriptExecutor)driver);
			jse.executeScript("arguments[0].click();",element );
  }
  @AfterTest
  public void atEnd()
  {
	  driver.quit();
  }
}

Output

PASSED: clickButton

===============================================
    Default test
    Tests run: 1, Failures: 0, Skips: 0
===============================================


===============================================
Default suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================

[TestNG] Time taken by [email protected]: 24 ms
[TestNG] Time taken by [email protected]: 38 ms
[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 0 ms
[TestNG] Time taken by [email protected]: 7 ms
[TestNG] Time taken by [email protected]: 6 ms
[TestNG] Time taken by [email protected]: 7 ms

5. Scroll the Browser

We can scroll the current page on the browser with executeScript("window.scrollBy(0,50)") method and passing the pixels as a parameter. In the code below, once the URL gets loaded, the page will scroll down to the end of the page with executeScript("window.scrollBy(0,document.body.scrollHeight)") method. However, if we want to scroll vertically downward or upward using pixels we can just pass it to the parameter scrollby()

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class JSExecutor{
	
	public WebDriver driver;
	public String Url = "http://www.ebay.com";
	
	@BeforeTest
	public void setDriver()
	{
		driver = new FirefoxDriver();
		driver.get(Url);
	}
  @Test
  public void scrollPage()
  {         driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
			JavascriptExecutor jse = ((JavascriptExecutor)driver);
			jse.executeScript("window.scrollBy(0,document.body.scrollHeight)");
  }
  @AfterTest
  public void atEnd()
  {
	 driver.quit();
  }
}

Output

PASSED: scrollPage

===============================================
    Default test
    Tests run: 1, Failures: 0, Skips: 0
===============================================


===============================================
Default suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================

[TestNG] Time taken by [email protected]: 45 ms
[TestNG] Time taken by [email protected]: 42 ms
[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 1 ms
[TestNG] Time taken by [email protected]: 4 ms
[TestNG] Time taken by [email protected]: 2 ms
[TestNG] Time taken by [email protected]: 7 ms

6. Conclusion

This tutorial covered some of the Java Script method that we can implement on the browser by using JavaSriptExecutor interface of the Selenium WebDriver. In this way, we can perform the actions of JavaScript on the HTML DOM, Browser Object Model (BOM) as well as other functionality like getting URL of the page, domain name of the web site, frames etc by using the JavaScriptExecutor interface.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

Be the First to Comment!

Notify of
avatar
wpDiscuz