0% found this document useful (0 votes)
70 views9 pages

Using JavaScriptExecutor in Selenium

The document discusses how to use JavaScriptExecutor in Selenium to execute JavaScript commands on a web page. JavaScriptExecutor provides two methods - executeScript and executeAsyncScript - to run JavaScript synchronously or asynchronously. It can be used to perform actions like clicking elements, handling alerts, extracting page data, and scrolling that may not be possible with regular Selenium locators. Some examples demonstrated include waiting for an element using executeAsyncScript, clicking a button and displaying an alert using executeScript, and scrolling down a page. JavaScriptExecutor allows enhancing Selenium tests by directly executing JavaScript on the browser.

Uploaded by

jeevi jeeva
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views9 pages

Using JavaScriptExecutor in Selenium

The document discusses how to use JavaScriptExecutor in Selenium to execute JavaScript commands on a web page. JavaScriptExecutor provides two methods - executeScript and executeAsyncScript - to run JavaScript synchronously or asynchronously. It can be used to perform actions like clicking elements, handling alerts, extracting page data, and scrolling that may not be possible with regular Selenium locators. Some examples demonstrated include waiting for an element using executeAsyncScript, clicking a button and displaying an alert using executeScript, and scrolling down a page. JavaScriptExecutor allows enhancing Selenium tests by directly executing JavaScript on the browser.

Uploaded by

jeevi jeeva
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
  • Introduction to JavaScriptExecutor
  • JavaScriptExecutor Methods
  • Examples Using JavaScriptExecutor

JavaScriptExecutor in Selenium

WebDriver with Example


What is JavaScriptExecutor?
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.

Why do we need JavaScriptExecutor?


In Selenium Webdriver, locators like XPath, CSS, etc. are used to identify and perform
operations on a web pageat is Software Testing Why Testing is Important

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 ([Link]) in the script as to use
JavaScriptExecutor.

JavaScriptExecutor Methods
1. executeAsyncScript

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.
2. executeScript

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

 Boolean
 Long
 String
 List
 WebElement.

The basic syntax for JavascriptExecutor is given below:

Syntax:

JavascriptExecutor js = (JavascriptExecutor) driver;


[Link](Script,Arguments);

 Script – This is the JavaScript that needs to execute.


 Arguments – It is the arguments to the script. It's optional.

Example of executeAsyncScript
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.

Example 1: Performing a sleep in the browser under test.


In this scenario, we will use "Guru99" demo site to illustrate executeAsyncScript. In this
example, you will

 Launch the browser.


 Open site "[Link]
 Application waits for 5 sec to perform a further action.

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 [Link];

import [Link];
import [Link];
import [Link];
import [Link];

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.


[Link]("[Link]

//Maximize window
[Link]().window().maximize();

//Set the Script Timeout to 20 seconds


[Link]().timeouts().setScriptTimeout(20, [Link]);

//Declare and set the start time


long start_time = [Link]();

//Call executeAsyncScript() method to wait for 5 seconds


[Link]("[Link](arguments[[Link] -
1], 5000);");

//Get the difference (currentTime - startTime) of times.


[Link]("Passed time: " + ([Link]() -
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-
[Link]
log4j:WARN No appenders could be found for logger
([Link]).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See [Link] for more
info.
Passed time: 5022
PASSED: Login

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

Example of executeScript
For executeScript, we will see three different example one by one.

1) Example: Click a button to login and generate Alert


window using JavaScriptExecutor.
In this scenario, we will use "Guru99" demo site to illustrate JavaScriptExecutor. In this
example,

 Launch the web browser


 open the site "[Link]
 login with credentials

 Display alert window on successful login.


import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

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.


[Link]("[Link]

WebElement button =[Link]([Link]("btnLogin"));

//Login to Guru99
[Link]([Link]("uid")).sendKeys("mngr34926");
[Link]([Link]("password")).sendKeys("amUpenu");

//Perform Click on LOGIN button using JavascriptExecutor


[Link]("arguments[0].click();", button);

//To generate Alert window using JavascriptExecutor. Display the alert


message
[Link]("alert('Welcome to Guru99');");

}
}

Output: When the code is executed successfully. You will observe

 Successful click on login button and the


 Alert window will be displayed (see image below).
2) Example: Capture Scrape Data and Navigate to different
pages using JavaScriptExecutor.
Execute the below selenium script. In this example,

 Launch the site


 Fetch the details of the site like URL of the site, title name and domain name of the
site.
 Then navigate to a different page.

import [Link];
import [Link];
import [Link];
import [Link];

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.
[Link]("[Link]

//Fetching the Domain Name of the site. Tostring() change object to name.
String DomainName = [Link]("return
[Link];").toString();
[Link]("Domain name of the site = "+DomainName);

//Fetching the URL of the site. Tostring() change object to name


String url = [Link]("return [Link];").toString();
[Link]("URL of the site = "+url);

//Method [Link] fetch the Title name of the site. Tostring() change
object to name
String TitleName = [Link]("return [Link];").toString();
[Link]("Title of the page = "+TitleName);

//Navigate to new Page i.e to generate access page. (launch new url)
[Link]("[Link] = '[Link]
}
}

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-
[Link]

log4j:WARN No appenders could be found for logger


([Link]).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See [Link] for more
info.
Domain name of the site = [Link]
URL of the site = [Link]
Title of the page = Guru99 Bank Home Page
PASSED: Login

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

3) Example: Scroll Downusing JavaScriptExecutor.


Execute the below selenium script. In this example,

 Launch the site


 Scroll down by 600 pixel

import [Link];
import [Link];
import [Link];
import [Link];

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.


[Link]("[Link]

//Maximize window
[Link]().window().maximize();

//Vertical scroll down by 600 pixels


[Link]("[Link](0,600)");
}
}

Output: When above code is executed, it will scroll down by 600 pixels (see image below).

(https://www.guru99.com/images/ccna/061516_1127_ExecuteJava1.png)JavaScriptExecutor in Selenium 
WebDriver with Example
What
2. executeScript
This method executes JavaScript in the context of the currently selected frame or window in 
Selenium. The s
Step 2) Then, use executeAsyncScript() to wait 5 seconds.
Step 3) Then, get the current time.
Step 4) Subtract (current time
(https://www.guru99.com/images/ccna/061516_1127_ExecuteJava2.png)}
Output: Successfully displayed the passed time more than
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import or
(https://www.guru99.com/images/ccna/061516_1127_ExecuteJava3.png)2) Example: Capture Scrape Data and Navigate to different
(https://www.guru99.com/images/ccna/061516_1127_ExecuteJava4.png)        //Launching the Site.
        driver.get("http://de
(https://www.guru99.com/images/ccna/061516_1127_ExecuteJava5.png)log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html
(https://www.guru99.com/images/ccna/061516_1127_ExecuteJava6.png)        //Creating the JavascriptExecutor interface object

You might also like