JavaScriptExecutor in Selenium WebDriver with Example
What is JavaScript?
JavaScript is the language chosen inside the browser to interact with HTML, which states that a browser has JavaScript implementation in it and understands the JavaScript commands.
What is JavaScriptExecutor?
JavaScriptExecutor is an interface that provides a way to execute the JavaScript from Selenium Webdriver. To run javascript on the current page or selected window JavaScriptExecutor supply two methods “executeAsyncScript” and “executescript”.
Why do we need to perform operations using JavaScriptExecutor?
Using Selenium Webdriver you can perform any kind of operations like sending the text, click on a button, and click on a radio button, select the drop-downs. So, in that case, why we need to perform operations using JavaScript is because in some applications on some web elements the actual selenium webdriver commands will not work even though we write the code correctly. In those scenarios, to perform the operations we take the help of JavaScript. By using the JavaScriptExecutor interface you can perform those operations. For example, if we want to handle any dropdown then we use a select class provided by selenium.Similarly, for handling JavaScript operations selenium webdriver provides JavaScriptExecutor as an interface. There is no need to add for an extra plugin or add-on. To use JavaScriptExecutor you just need to import (org.openqa.selenium.JavascriptExecutor) in the script.
JavaScriptExecutor Methods
- executeAsyncScript
The executeAsyncScript command executes the JavaScript as an async snippet in the context of the currently selected window or frame. The script will be executed as the body of an anonymous function. We use the ‘return’ keyword to store the return value and provide a variable name in the input field value.
- executeScript
This method executes JavaScript in the context of the presently selected window or frame in Selenium. In this method the script which we used runs in the body of an anonymous function and also passes arguments that are complicated to it.
The script will return the values and the data types returned are
- Long
- String
- List
- WebElement.
- Boolean
The basic syntax for JavascriptExecutor:
Package:
import org.openqa.selenium.JavascriptExecutor;
Syntax:
JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript(Script,Arguments);
Script – To execute the JavaScript
Arguments –The arguments we pass to the script(Optional). May be empty.
Returns –One of Boolean, String, Long, List, WebElement, or null.
Let’s look at some scenarios we could handle using this JavaScript Interface:
- To click on a Button using JavaScript in Selenium WebDriver
js.executeScript("document.getElementById('enter element id').click();"); //or js.executeScript("arguments[0].click();", okButton);
- To generate Alert Pop window in Selenium WebDriver
js.executeScript("alert('Welcome To SeleniumTesting');");
- Typing Text without using sendKeys() method in Selenium WebDriver
js.executeScript("document.getElementById(id').value='someValue';"); js.executeScript("document.getElementById('Email').value='SeleniumTesting.com';");
- To handle the Checkbox in Selenium WebDriver
js.executeScript("document.getElementById('enter element id').checked=false;");
- To print the Title of a webpage
String titleText = js.executeScript("return document.title;").toString(); System.out.println(titleText);
- Refreshing the browser window using Javascript
((JavascriptExecutor)driver).executeScript(“history.go(0)”);
- To get entire webpage innertext in Selenium WebDriver
String innerText = js.executeScript(" return document.documentElement.innerText;").toString(); System.out.println(innerText);
- To make the checkbox has checked
((JavaScriptExecutor)driver.ExecuteScript(“document.querySelectorAll(‘input[value = read]’)[0].click()”);
- To get the Domain of a web page
((JavascriptExecutor)driver).executeScript(“return document.domain;”).toString();
- To get the URL of the web Page
((JavascriptExecutor)driver).executeScript(“return document.URL;”).toString();
- To Scroll the Page
To scroll the page vertically for 600px we use the following code
((JavascriptExecutor)driver).executeScript(“window.scrollBy(0,600)”);
To scroll the page vertically till the end we use the following code
((JavascriptExecutor)driver).executeScript(“window.scrollBy(0,document.body.scrollHeight)”);
- To navigate to the other Page
((JavascriptExecutor)driver).executeScript(“window.location=’http://SeleniumTesting.com’”);
- To get the Height and Width of a web page
((JavascriptExecutor)driver).executeScript(“return window.innerHeight;”).toString();((JavascriptExecutor)driver).executeScript(“return window.innerWidth;”).toString();
Example 1: Performing a sleep operation in the browser.
Scenario:
- Launch the browser.
- Open site “http://www.facebook.com”
- To perform further action the Application waits for 5 sec.
package SamplePackage; import java.util.concurrent.TimeUnit; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.Test; public class TestJava { @Test public void Login() { System.setProperty("webdriver.chrome.driver","F:\\drivers\\chromedriver.exe"); //create chrome instance driver = new ChromeDriver(); JavascriptExecutor js = (JavascriptExecutor)driver; //Launching the Site. driver.get("http://www.facebook.com"); //Maximize window driver.manage().window().maximize(); //Set the Script Timeout to 10 seconds driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS); //Declare and set the start time long start_time = System.currentTimeMillis(); //Calling executeAsyncScript() method and wait for 5 seconds js.executeAsyncScript("window.setTimeout(arguments[arguments.length - 1], 5000);"); //Get the difference (currentTime - startTime) of times. System.out.println("Passed time: " + (System.currentTimeMillis() - start_time)); } }
Example 2: Below program will handle some of the scenarios we use in while writing scripts.
package seleniumTesting; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.Test; public class JavaScriptExecutorClass { static WebDriver driver; @Test public static void javaScriptExeMethod(){ System.setProperty("webdriver.chrome.driver","F:\\drivers\\chromedriver.ex //create chrome instance driver = new ChromeDriver(); driver.get("https://www.gmail.com"); WebElement loginButton = driver.findElement(By.xpath("//*[@id='next']")); JavascriptExecutor js = (JavascriptExecutor)driver; *//Typing the text in Selenium WebDriver without using sendKeys() method js.executeScript("document.getElementById('some id').value='someValue';"); js.executeScript("document.getElementById('Email').value='SeleniumTesting.com';");*/ /*//To click a button using JavaScript //js.executeScript("arguments[0].click();", okButton); //or js.executeScript("document.getElementById('enter element id').click();"); js.executeScript("document.getElementById(ok).click();");*/ /*//to handle checkbox js.executeScript("document.getElementById('enter element id').checked=false;"); /*//to generate Alert Pop window in selenium js.executeScript("alert('Java world);");*/ /*//to refresh browser window using Javascript ((JavascriptExecutor)driver).executeScript(“history.go(0)”); */ /*// to get the innertext of the webpage in Selenium String innerText = js.executeScript(" return document.documentElement.innerText;").toString(); System.out.println(innerText); /*//to get the Title of our webpage String titleText = js.executeScript("return document.title;").toString(); System.out.println(titleText); /*//to get the domain String dText = js.executeScript("return document.domain;").toString(); System.out.println(dText);*/ /*//to get the URL of our webpage String urlText = js.executeScript("return document.URL;").toString(); System.out.println(urlText);*/ /*//to perform Scroll on application using Selenium //Vertical scroll - down by 600 pixels ((JavascriptExecutor)driver).executeScript(“window.scrollBy(0,600)”); // we use the code for scrolling till the bottom of the page //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.seleniumtesting.com");*/ } }
Example 3: Scroll Down using JavaScriptExecutor.
Execute the below selenium script.
- Launch the site
- Scroll down by 500 pixel
package SamplePackage; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.Test; public class ScrollDown_Test { @Test public void Login() { System.setProperty("webdriver.chrome.driver","F:\\drivers\\chromedriver.exe"); //create chrome instance WebDriver driver = new ChromeDriver(); //Creating the JavascriptExecutor interface object by Typecasting JavascriptExecutor js = (JavascriptExecutor)driver; //Launching the Site. driver.get("http://www.facebook.com/"); //Maximize window driver.manage().window().maximize(); //Vertical scroll down by 500 pixels js.executeScript("window.scrollBy(0,500)"); } }
Conclusion:
We use JavaScriptExecutor whenever Selenium Webdriver fails to click on any web element due to some issues.
- To handle, JavaScriptExecutor offers two methods “executeAsyncScript” and “executescript”.
- JavaScriptExecutor will execute the JavaScript using Selenium Webdriver.
- Fetched URL, the title of the page, and domain name using JavaScriptExecutor.
- Generate the ‘Alert’ window by using JavaScriptExecutor in Selenium Webdriver.
- Scroll the window to down using JavaScriptExecutor.
- Will navigate to the different pages using JavaScriptExecutor.