• Selenium Video Tutorials

Selenium WebDriver - JavaScript Executor



Selenium Webdriver are used to run JavaScript commands to communicate with elements appearing within a browser on a page. This is done with the help of the JavaScriptExecutor interface. Sometimes, the locators available in Selenium Webdriver fail to interact with the elements on a page, in those scenarios we can take the help of the JavaScriptExecutor methods.

Basic Methods to Run JavaScript Commands

There are multiple the methods available in JavaScriptExecutor interface. They are listed below −

executeScript Method

This method is used to execute JavaScript in a window or frame currently active. It is an anonymous function, supports various data types like WebElements, Long, String, Lists, and Boolean.

executeAsyncScript Method

It is a multi-threaded approach to execute individual JavaScript tasks on window or frame in currently active. It allows page parsing to continue, optimizing performance and providing great flexibility. This method enables the asynchronous JavaScript to be executed in an optimal way.

Steps to Execute the JavaScript commands

The steps to execute JavaScript commands along with Selenium Webdriver using the JavaScriptExecutor interface are listed below −

Step 1 − Package import for JavaScriptExecutor.

Step 2 − Creating a reference variable JavaScriptExecutor interface.

Step 3 − Calling the JavaScriptExecutor methods.

Syntax

import org.openqa.selenium.JavascriptExecutor;
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript(script, args);

Example

Let us take an example of the below page, where we would open an application with a URL − Selenium Automation Practice Form.

Then, get the text: Selenium - Automation Practice Form, and domain as www.tutorialspoint.com. Next we would enter the text Selenium in the input box beside the Name label.

Selenium JavaScript Executor 1

Then, we would click on the Login, because of that we navigate to a new page having the text Welcome, Login In. We would refresh the browser then and get the text, URL and domain as Welcome, Login In, Selenium Automation Practice Form and www.tutorialspoint.com respectively.

Selenium JavaScript Executor 2

Code Implementation

package org.example;

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 java.util.concurrent.TimeUnit;

public class JavaScriptsExe {
   public static void main(String[] args) throws InterruptedException {

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

      // adding implicit wait of 25 secs
      driver.manage().timeouts().implicitlyWait(25, TimeUnit.SECONDS);

      // Creating a reference variable JavaScriptExecutor interface.
      JavascriptExecutor j = (JavascriptExecutor) driver;

      // launching a URL
      j.executeScript("window.location = 'https://www.tutorialspoint.com/selenium/practice/selenium_automation_practice.php'");

      // getting current URL
      String url =  j.executeScript("return document.URL;").toString();
      System.out.println("Get the current URL: " + url);

      //identify text
      WebElement t = driver.findElement(By.xpath("/html/body/div/header/div[2]/h1"));

      // get text
      String text = (String) j.executeScript("return arguments[0].innerText", t);
      System.out.println("Text is: " + text);

      // getting current domain
      String domain = j.executeScript("return document.domain;").toString();
      System.out.println("Get the current domain: " + domain);

      // enter text in input box
      WebElement e = driver.findElement(By.xpath("//*[@id='name']"));
      j.executeScript("arguments[0].value='Selenium';", e);

      // get text entered
      String text1 = (String) j.executeScript("return arguments[0].value", e);
      System.out.println("Entered text is: " + text1);

      // perform click
      WebElement b = driver.findElement(By.xpath("//*[@id='collapseTwo']/div/ul/li[2]/a"));
      j.executeScript("arguments[0].click();", b);

      //identify text
      WebElement w = driver.findElement(By.xpath("//*[@id='signInForm']/h1"));

      // get text after click
      String text2 = (String) j.executeScript("return arguments[0].innerText", w);
      System.out.println("Text found after clicking is: " + text2);

      // refresh browser
      j.executeScript("history.go(0)");

      // getting current URL after browser refresh
      String url1 =  j.executeScript("return document.URL;").toString();
      System.out.println("Get the current URL after browser refresh: " + url1);

      //identify text again after refresh
      WebElement y = driver.findElement(By.xpath("//*[@id='signInForm']/h1"));

      // get text after refresh
      String text3 = (String) j.executeScript("return arguments[0].innerText", y);
      System.out.println("Text found after refresh is: " + text3);

      // getting current domain after browser refresh
      String domain1 = j.executeScript("return document.domain;").toString();
      System.out.println("Get the current domain after browser refresh: " + domain1);

      // Quit browser
      driver.quit();
   }
}

Output

Get the current URL:
 https://www.tutorialspoint.com/selenium/practice/selenium_automation_practice.php
Text is: Selenium - Automation Practice Form
Get the current domain: www.tutorialspoint.com
Entered text is: Selenium
Text found after clicking is: Welcome, Login In
Get the current URL after browser refresh:
https://www.tutorialspoint.com/selenium/practice/login.php
Text found after refresh is: Welcome, Login In
Get the current domain after browser refresh:
www.tutorialspoint.com

Process finished with exit code 0

In the above example, we had launched a URL and obtained the current URL with the message in the console - Getting the current URL: Selenium Automation Practice Form

Then retrieved the text and domain with the message in the console - Text is: Selenium - Automation Practice Form and Getting the current domain: www.tutorialspoint.com respectively.

Next, we entered the text Selenium in an input box and retrieved its value with the message in the console - Entered text is: Selenium. Then, we clicked the Login link and got the text after navigation with the message in console: Text found after clicking is: Welcome, Login In. Finally, we had refreshed the page and obtained current URL, text and domain of the page with the messages in the console - Get the current URL after browser refresh: Selenium Useful Resources

Text found after refresh is: Welcome, Login In, and Get the current domain after browser refresh: www.tutorialspoint.com respectively.

Finally, the message Process finished with exit code 0 was received, signifying successful execution of the code.

Example - Scroll Down With JavaScriptExecutor

Let us now discuss how to perform a scroll down to the bottom of a web page with the help of scrollTo method and get the button Login appearing at that page bottom as shown in the below image. The scrollTo method takes two parameters - horizontal and vertical vertices.

Selenium JavaScript Executor 3

Code Implementation

package org.example;

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 java.util.concurrent.TimeUnit;

public class PageDownsScroll {
   public static void main(String[] args) throws InterruptedException {

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

      // adding implicit wait of 12 secs
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);

      //Opening the webpage where we will perform the scroll
      driver.get("https://www.tutorialspoint.com/selenium/practice/selenium_automation_practice.php");

      // JavascriptExecutor to scrolling to page bottom
      JavascriptExecutor javascriptExecutor = (JavascriptExecutor) driver;
      javascriptExecutor.executeScript("window.scrollBy(0,document.body.scrollHeight)");

      // access element at page bottom after scrolling
      WebElement w = driver.findElement(By.xpath("//*[@id='practiceForm']/div[11]/input"));

      System.out.println("Verify element presence after scroll down: " + w.isDisplayed());

      // quit the browser
      driver.quit();
   }
}

Output

Verify element presence after scroll down: true

To get more information on Scrolling actions with Selenium Webdriver, please refer to the link Selenium Webdriver Scroll Operations.

Example - Create Alert with JavaScriptExecutor

Let us take an example of the below page where we would create an alert on a webpage using JavaScriptExecutor and obtain the text Tutorialspoint.

Selenium JavaScript Executor 4

Code Implementation

package org.example;

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;

public class JavaScriptAlert {
   public static void main(String[] args) throws InterruptedException {

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

      // adding implicit wait of 20 secs
      driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

      // Creating a reference variable JavaScriptExecutor interface
      JavascriptExecutor j = (JavascriptExecutor) driver;

      //  create an Alert
      j.executeScript("alert('Tutorialspoint!!!');");

      // switch driver context to alert
      Alert alrt = driver.switchTo().alert();

      // Get alert text
      String s = alrt.getText();
      System.out.println("Alert text is: " + s);

      // Quit browser
      driver.quit();
   }
}

Output

Alert text is: Tutorialspoint!!!

In the above example, we had created an alert and obtained its text with the message in the console - Alert text is: Tutorialspoint!!!

Example - Select Checkbox with JavaScriptExecutor

Let us take another example of the below page, where would check the checkbox to select the Main Level 2 option with the help of JavaScript Executor −

Selenium JavaScript Executor 5

Code Implementation

package org.example;

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;

public class JavaScriptHandlesCheckbox {
   public static void main(String[] args) throws InterruptedException {

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

      // adding implicit wait of 20 secs
      driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

      // Creating a reference variable JavaScriptExecutor interface
      JavascriptExecutor j = (JavascriptExecutor) driver;

      // Opening the webpage where we will check checkbox
      driver.get("https://www.tutorialspoint.com/selenium/practice/check-box.php");

      // identify checkbox with xpath
      WebElement chkbox = driver.findElement(By.xpath("//*[@id='c_bs_2']"));

      // check the checkbox
      j.executeScript("document.getElementById('c_bs_2').checked=true;");

      // check if checkbox is selected
      System.out.println("Checkbox is selected: " + chkbox.isSelected());

      // Quitting browser
      driver.quit();
   }
}

Output

Checkbox is selected: true

In the above example, we had checked a checkbox and validated if it is checked with the message in the console - Checkbox is selected: true

Conclusion

This concludes our comprehensive take on the tutorial on Selenium Webdriver JavaScript Executor. We’ve started with describing basic methods to run JavaScript commands, steps To execute the JavaScript commands, and examples to illustrate how to handle JavaScript Executor in Selenium Webdriver. This equips you with in-depth knowledge of the Selenium Webdriver JavaScript Executor. It is wise to keep practicing what you’ve learned and exploring others relevant to Selenium to deepen your understanding and expand your horizons.

Advertisements