Selenium

Selenium Javascriptexecutor Tutorial

Photo of Sarad DhungelSarad DhungelMarch 20th, 2017Last Updated: April 8th, 2019
0 263 4 minutes read

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.
 
 
 
 
 
 

 
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 andget() method will invoke the given URL. Then,@Test will run where, JavaScriptExecutor gets instantiated andexecuteScript() 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";@BeforeTestpublic 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 suiteTotal tests run: 1, Failures: 0, Skips: 0===============================================[TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@e580929: 75 ms[TestNG] Time taken by org.testng.reporters.jq.Main@27f674d: 70 ms[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 1 ms[TestNG] Time taken by org.testng.reporters.EmailableReporter2@39ba5a14: 8 ms[TestNG] Time taken by org.testng.reporters.JUnitReportReporter@5b464ce8: 4 ms[TestNG] Time taken by org.testng.reporters.XMLReporter@7a79be86: 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 methodjse.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 andget() 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";@BeforeTestpublic 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 suiteTotal tests run: 1, Failures: 0, Skips: 0===============================================[TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@e580929: 21 ms[TestNG] Time taken by org.testng.reporters.jq.Main@27f674d: 37 ms[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 1 ms[TestNG] Time taken by org.testng.reporters.EmailableReporter2@39ba5a14: 8 ms[TestNG] Time taken by org.testng.reporters.JUnitReportReporter@5b464ce8: 3 ms[TestNG] Time taken by org.testng.reporters.XMLReporter@7a79be86: 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";@BeforeTestpublic 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

Want to master Selenium?
Subscribe to our newsletter and download theSeleniumProgramming Cookbookright 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!

Thank you!

We will contact you soon.

PASSED: clickButton===============================================    Default test    Tests run: 1, Failures: 0, Skips: 0==============================================================================================Default suiteTotal tests run: 1, Failures: 0, Skips: 0===============================================[TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@e580929: 24 ms[TestNG] Time taken by org.testng.reporters.jq.Main@27f674d: 38 ms[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 0 ms[TestNG] Time taken by org.testng.reporters.EmailableReporter2@39ba5a14: 7 ms[TestNG] Time taken by org.testng.reporters.JUnitReportReporter@5b464ce8: 6 ms[TestNG] Time taken by org.testng.reporters.XMLReporter@7a79be86: 7 ms

5. Scroll the Browser

We can scroll the current page on the browser withexecuteScript("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 withexecuteScript("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 parameterscrollby()

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";@BeforeTestpublic 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 suiteTotal tests run: 1, Failures: 0, Skips: 0===============================================[TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@e580929: 45 ms[TestNG] Time taken by org.testng.reporters.jq.Main@27f674d: 42 ms[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 1 ms[TestNG] Time taken by org.testng.reporters.EmailableReporter2@39ba5a14: 4 ms[TestNG] Time taken by org.testng.reporters.JUnitReportReporter@5b464ce8: 2 ms[TestNG] Time taken by org.testng.reporters.XMLReporter@7a79be86: 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 aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
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 ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Sarad DhungelSarad DhungelMarch 20th, 2017Last Updated: April 8th, 2019
0 263 4 minutes read
Photo of 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.
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.