Selenium
Chrome Options & Desiredcapabilities: AdBlocker, Incognito, Headless
What is Chrome Options class? Chrome options class is used to manipulate various properties of...
JavaScriptExecutor is an Interface that helps to execute JavaScript through Selenium Webdriver. JavaScriptExecutor provides two methods "executescript" & "executeAsyncScript" to run javascript on the selected window or current page.
In this tutorial, you will learn -
In Selenium Webdriver, locators like XPath, CSS, etc. are used to identify and perform operations on a web page.
In case, these locators do not work you can use JavaScriptExecutor. You can use JavaScriptExecutor to perform an desired operation on a web element.
Selenium supports javaScriptExecutor. There is no need for an extra plugin or add-on. You just need to import (org.openqa.selenium.JavascriptExecutor) in the script as to use JavaScriptExecutor.
With Asynchronous script, your page renders more quickly. Instead of forcing users to wait for a script to download before the page renders. This function will execute an asynchronous piece of JavaScript in the context of the currently selected frame or window in Selenium. The JS so executed is single-threaded with a various callback function which runs synchronously.
This method executes JavaScript in the context of the currently selected frame or window in Selenium. The script used in this method runs in the body of an anonymous function (a function without a name). We can also pass complicated arguments to it.
The script can return values. Data types returned are
The basic syntax for JavascriptExecutor is given below:
Syntax:
JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript(Script,Arguments);
Using the executeAsyncScript, helps to improve the performance of your test. It allows writing test more like a normal coding.
The execSync blocks further actions being performed by the Selenium browser but execAsync does not block action. It will send a callback to the server-side Testing suite once the script is done. It means everything inside the script will be executed by the browser and not the server.
In this scenario, we will use "gtupapers" demo site to illustrate executeAsyncScript. In this example, you will
Step 1) Capture the start time before waiting for 5 seconds ( 5000 milliseconds) by using executeAsyncScript() method.
Step 2) Then, use executeAsyncScript() to wait 5 seconds.
Step 3) Then, get the current time.
Step 4) Subtract (current time – start time) = passed time.
Step 5) Verify the output it should display more than 5000 milliseconds
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.Test;
public class JavaSE_Test {
@Test
public void Login()
{
WebDriver driver= new FirefoxDriver();
//Creating the JavascriptExecutor interface object by Type casting
JavascriptExecutor js = (JavascriptExecutor)driver;
//Launching the Site.
driver.get("http://demo.gtupapers.com/V4/");
//Maximize window
driver.manage().window().maximize();
//Set the Script Timeout to 20 seconds
driver.manage().timeouts().setScriptTimeout(20, TimeUnit.SECONDS);
//Declare and set the start time
long start_time = System.currentTimeMillis();
//Call executeAsyncScript() method to 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));
}
}
Output: Successfully displayed the passed time more than 5 seconds(5000 miliseconds) as shown below:
[TestNG] Running:
C:\Users\gauravn\AppData\Local\Temp\testng-eclipse-387352559\testng-customsuite.xml
log4j:WARN No appenders could be found for logger (org.apache.http.client.protocol.RequestAddCookies).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Passed time: 5022
PASSED: Login
===============================================
Default test
Tests run: 1, Failures: 0, Skips: 0
===============================================For executeScript, we will see three different example one by one.
In this scenario, we will use "gtupapers" demo site to illustrate JavaScriptExecutor. In this 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.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class JavaSE_Test {
@Test
public void Login()
{
WebDriver driver= new FirefoxDriver();
//Creating the JavascriptExecutor interface object by Type casting
JavascriptExecutor js = (JavascriptExecutor)driver;
//Launching the Site.
driver.get("http://demo.gtupapers.com/V4/");
WebElement button =driver.findElement(By.name("btnLogin"));
//Login to gtupapers
driver.findElement(By.name("uid")).sendKeys("mngr34926");
driver.findElement(By.name("password")).sendKeys("amUpenu");
//Perform Click on LOGIN button using JavascriptExecutor
js.executeScript("arguments[0].click();", button);
//To generate Alert window using JavascriptExecutor. Display the alert message
js.executeScript("alert('Welcome to gtupapers');");
}
}
Output: When the code is executed successfully. You will observe
Execute the below selenium script. In this example,
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class JavaSE_Test {
@Test
public void Login()
{
WebDriver driver= new FirefoxDriver();
//Creating the JavascriptExecutor interface object by Type casting
JavascriptExecutor js = (JavascriptExecutor)driver;
//Launching the Site.
driver.get("http://demo.gtupapers.com/V4/");
//Fetching the Domain Name of the site. Tostring() change object to name.
String DomainName = js.executeScript("return document.domain;").toString();
System.out.println("Domain name of the site = "+DomainName);
//Fetching the URL of the site. Tostring() change object to name
String url = js.executeScript("return document.URL;").toString();
System.out.println("URL of the site = "+url);
//Method document.title fetch the Title name of the site. Tostring() change object to name
String TitleName = js.executeScript("return document.title;").toString();
System.out.println("Title of the page = "+TitleName);
//Navigate to new Page i.e to generate access page. (launch new url)
js.executeScript("window.location = 'http://demo.gtupapers.com/'");
}
}
Output: When above code is executed successfully, it will fetch the details of the site and navigate to different page as shown below.
[TestNG] Running:
C:\Users\gauravn\AppData\Local\Temp\testng-eclipse-467151014\testng-customsuite.xml
log4j:WARN No appenders could be found for logger (org.apache.http.client.protocol.RequestAddCookies).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Domain name of the site = demo.gtupapers.com
URL of the site = http://demo.gtupapers.com/V4/
Title of the page = gtupapers Bank Home Page
PASSED: Login
===============================================
Default test
Tests run: 1, Failures: 0, Skips: 0
=============================================== Execute the below selenium script. In this example,
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class JavaSE_Test {
@Test
public void Login()
{
WebDriver driver= new FirefoxDriver();
//Creating the JavascriptExecutor interface object by Type casting
JavascriptExecutor js = (JavascriptExecutor)driver;
//Launching the Site.
driver.get("http://moneyboats.com/");
//Maximize window
driver.manage().window().maximize();
//Vertical scroll down by 600 pixels
js.executeScript("window.scrollBy(0,600)");
}
}
Output: When above code is executed, it will scroll down by 600 pixels (see image below).
Summary:
JavaScriptExecutor is used when Selenium Webdriver fails to click on any element due to some issue.
What is Chrome Options class? Chrome options class is used to manipulate various properties of...
During test automation of web-based application, there comes a need for the page to be refreshed...
What is Link Text in Selenium? A Link Text in Selenium is used to identify the hyperlinks on a web...
{loadposition top-ads-automation-testing-tools} Selenium is an open-source automated testing tool....
What is Ajax? AJAX stands for Asynchronous JavaScript & XML, and it allows the Web page to...
Why do you need Find Element/s command? Interaction with a web page requires a user to locate the web...