0% found this document useful (0 votes)
45 views

JavaScriptExecutor in Selenium WebDriver

Uploaded by

ASHUTOSH TRIVEDI
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

JavaScriptExecutor in Selenium WebDriver

Uploaded by

ASHUTOSH TRIVEDI
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

JavaScriptExecutor in Selenium WebDriver

 JavaScriptExecutor in Selenium is an interface that executes JavaScript


code snippets within the context of browser. It is implemented through the
RemoteWebDriver class.

 We use JavaScriptExecutor interface to perform some advanced operations


that are not yet supported by Selenium WebDriver. The general syntax of
JavascriptExecutor is as follows:

public interface JavascriptExecutor

Selenium supports JavaScriptExecutor without any separate script, an extra plugin,


or add-on. We just need to import a package
(org.openqa.selenium.JavascriptExecutor) in the script to use JavaScriptExecutor.

Basic Syntax for JavaScriptExecutor

The basic syntax to use JavaScriptExecutor in Selenium WebDriver is as follows:


JavascriptExecutor js = (JavascriptExecutor)driver; // Casting.
js.executeScript( Script, Arguments );

JavascriptExecutor Methods in Selenium

The most common methods of JavaScriptExecutor used in Selenium is as follows:


1. executeScript():
The executeScript() method is used to execute JavaScript code in the context of the
currently selected frame or window. The script provided in this method will be
executed as the body of an anonymous function (anonymous function means a
function without a name).
The general syntax for this method is as follows:
executeScript( String script, Object... args) : Object

It takes two input parameters such as script and args. The parameter script is a
JavaScript code that has to be executed. Within the script, we will use document
object that refers to the current document.
The document object represents a web page that is displayed in the full browser
window, frame, or layer. An object is created with each document that is loaded by
the browser.

If the JavaScript code returns a value (i.e. if the script contains a return statement),
then we need to use the return keyword. The returned value is as follows:
1. WebElement for HTML element.
2. Double for decimal.
3. Long for non-decimal number.
4. Boolean for boolean.
5. String for all other cases.
6. Null if there is no return value.

Based on the type of return value, we will need to cast the executeScript() method.
For decimal values, Double will be used. For text value, String will be used. If
JavaScript code returns an HTML element, WebElement can be used, and so on.
For example:
JavascriptExecutor js = (JavascriptExecutor)driver; // Casting.

String title = (String) js.executeScript("return document.title"); // Casting.


System.out.println(title);

The second parameter is the args. args is the argument to the script. It may be
empty. Arguments such as a number, a boolean, a String, WebElement, or a List of
any combination of the above can also be passed to the JavaScript code being
executed by using the executedScript() method.

How to Get Title of Webpage using JavaScriptExecutor in Selenium?

Scenario to Automate:
In this scenario, we will call JavaScript code to return the title of the Google home
page. In this example, we will automate the following scenario. They are as
follows:
a. Launch the Firefox browser.
b. Open the URL https://www.google.com of Google home page.
c. Get the title of the home page.
d. Close the browser.
The Java program code to automate the above scenario is as follows:
package testing;

import java.time.Duration;

import org.openqa.selenium.JavascriptExecutor;

import org.openqa.selenium.WebDriver;

import org.testng.annotations.BeforeClass;

import org.testng.annotations.Test;

import base.BaseTest;

public class JavaScriptExecutorGetTitleDemo extends BaseTest {

WebDriver webDriver;

@BeforeClass

public void setup() {

webDriver=getWebDriver();

@Test

public void srollingPageTest() throws InterruptedException {


// Maximize the window.

webDriver.manage().window().maximize();

webDriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

// Create the JavascriptExecutor interface object by Type casting of


WebDriver instance.

JavascriptExecutor js = (JavascriptExecutor)webDriver;

// Call executeScript() method to get the title of web page.

Object title = js.executeScript("return document.title"); // Here, the


return type of executeScript() method is object.

// Since the return type of executeScript() method is object, we need to


perform type casting to get title in String text.

String getTitle = (String)title;

System.out.println("Title of Home page: " +getTitle);

// The last three lines of code can also be written in one line like this:

// String getTitle = (String)js.executeScript("return document.title");

}
}

How to Send Text and Click on Element using JavaScriptExecutor in


Selenium?

2. Let’s take another scenario where we will send a text in the search box and click
on the submit button by using JavaScriptExecutor. We will use the same URL.
Here, we will not use the sendKeys() method.

package testing;

import java.time.Duration;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import base.BaseTest;

public class JavaScriptExecutorGetTitleDemo extends BaseTest {

WebDriver webDriver;

@BeforeClass
public void setup() {
webDriver=getWebDriver();
}

@Test

public void sendTextPageTest() throws InterruptedException {


// Maximize the window.
webDriver.manage().window().maximize();

webDriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
// Locate the WebElement Searchbox and submit button of Google
home page by By.xpath.
WebElement search =
webDriver.findElement(By.xpath("//input[@name = 'q']"));
WebElement submit =
webDriver.findElement(By.xpath("//input[@name = 'btnK']"));

// Create the JavascriptExecutor interface object by Type casting of


WebDriver instance.
JavascriptExecutor js = (JavascriptExecutor)webDriver;

// Send a text value "Selenium" using JavascriptExecutor.


js.executeScript("arguments[0].value = 'Selenium'", search); // Line
1

// Click on submit button using JavascriptExecutor.


js.executeScript("arguments[0].click()", submit); // Line 2

// We can write Line 1 and Line 2 code in a single line like this:
// js.executeScript("arguments[0].value = 'Selenium',
arguments[1].click()", search, submit);

System.out.println("Test successful");
}
}

How to Scroll Up and Down in Selenium WebDriver

What is Scrollbar?

A Scrollbar is an interaction technique that allows us to scroll the continuous text,


pictures, or any other content in horizontal or verticle direction on a device’s
screen when the web page scroll does not fit into the visible area of the screen.
It is used to view the content on a screen by scrolling the web page up, down, left,
or right. There are mainly two types of scrollbars. They are horizontal and vertical
scroll bars that can be seen in the below figure.
Let’s take different example scenarios based on the scrolling of the web page in
Selenium.

How to Scroll Down Web Page by Pixel in Selenium?

To scroll down the web page by pixel in Selenium, we will use scrollBy() method
provided by JavaScript 1.2. This method scrolls the web page in the window by a
specified number of pixels left or right and up or down. The syntax for scrollBy()
method of JavaScript is as follows:
window.scrollBy(int x-pixels, int y-pixels);
The scrollBy() method is called by using the window object by passing the number
of pixels as parameter values to the method. The object of window is automatically
created by the browser. The window object represents the browser’s window.

All global variables, functions/methods, and objects of JavaScript can be called by


using the window object because they are automatically members of the window
object.
Here, x-pixels is the numeric value passed to the method that represents the
number of horizontal pixels by which we will scroll the window in the horizontal.
x-pixels represents number at x-axis.
Let’s automate a simple scenario in which we will scroll webpage down by 1000
pixels vertically.
Scenario to Automate:
a. Launch the Firefox web browser.
b. Open the website “https//www.yahoo.com“.
c. Scroll home page down by 1000 pixels vertical.
Let’s start coding to automate the above scenario.
Program code 1:
package testing;

import java.time.Duration;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import base.BaseTest;

public class VerticalScrollDown extends BaseTest {

WebDriver webDriver;

@BeforeClass
public void setup() {
webDriver=getWebDriver();
}

@Test
public void sendTextPageTest() throws InterruptedException {
// Maximize the window.
webDriver.manage().window().maximize();
webDriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
// Create the JavaScriptExecutor interface object by type casting of
WebDriver instance.
JavascriptExecutor js = (JavascriptExecutor)webDriver;

// Call scrollBy() method of Javascript using window object with


passing number of pixels as parameter values.
// Call executeScript() method of JavascriptExecutor interface with
passing window.scrollBy() as parameter value.

js.executeScript("window.scrollBy(0,1000)"); // It will scroll down


the page by 1000 pixel vertical
}
}

How to Scroll Down Web Page by Visibility of Element?

Let’s take an example where we will scroll down web page by the visibility of an
element.
Scenario to Automate:
1. Launch the Firefox browser.
2. Open the URL “https://selenium08.blogspot.com/2020/02/vertical-scroll.html”
in the Firefox browser.
3. Now, scroll the web page until the mentioned element is visible on the current
page.
[adinserter block=”2″]
To scroll down the web page until the visibility of the mentioned element, we will
use a scrollIntoView() method of JavaScript. The scrollIntoView() method is used
to scroll the web page or browser window until the mentioned element is visible on
the screen.
The general syntax for scrollIntoView() method of JavaScript is as follows:
element.scrollIntoView(alignTo)
This method accepts a boolean value that is optional. It does not return anything. A
boolean value indicates the type of alignment. Look at the source code to test the
above scenario.
Program code 2:
package testing;

import java.time.Duration;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import base.BaseTest;

public class ScrollByVisibleElement extends BaseTest {

WebDriver webDriver;

@BeforeClass
public void setup() {
webDriver=getWebDriver();
}

@Test
public void sendTextPageTest() throws InterruptedException {
// Maximize the window.
webDriver.manage().window().maximize();

// Locate web element "Health" by By.xpath.


WebElement element = webDriver.findElement(By.xpath("//a[text()
= 'Health']"));

// Create the JavaScriptExecutor interface object by Type casting of


WebDriver instance.
JavascriptExecutor js = (JavascriptExecutor)webDriver;

// Call scrollIntoView() method of Javascript using magic variable


arguments[0].
// Call executeScript() method JavascriptExecutor interface with
passing arguments[0].scrollIntoView() as parameter values.

js.executeScript("arguments[0].scrollIntoView();", element); // It
will scroll down the page by visibility of element "Health".
}
}

In the statement “js.executeScript(“arguments[0].scrollIntoView()”, element );”,


arguments[0] represents first index of page starting at 0 whereas, ” element ” is the
locator on the web page.

Now run the above test script and observe the output on the web page. Web page
scrolls down until the visibility of the element or not. The output of the above
scenario is shown in the below screenshot.
How to Scroll Down at the Bottom of Webpage?

Let’s take the same URL as and we will scroll down till the bottom of the page.
The scrollTo() method of Javascript scrolls until the end of the page. This method
scrolls the web page to the specified coordinates. The syntax for the scrollTo()
method is as follows:
window.scrollTo(int x, int y)
This method accepts two integer values as parameters in pixels and returns
nothing.
For example:
Scroll the web page to position “300” horizontally and “500” vertically:
window.scrollTo(300, 500);
Look at the following source code step by step.
Program code 3:
Program code 3:
package scrollUpandDown;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class ScrollByPage {


public static void main(String[] args)
{
// Create driver object.
WebDriver driver = new FirefoxDriver();

// Maximizing the window.


driver.manage().window().maximize();

// Launch the application.


String URL = "https://selenium08.blogspot.com/";
driver.get(URL);

// Create the JavascriptExecutor interface object by Type casting of WebDriver


instance.
JavascriptExecutor js = (JavascriptExecutor) driver;

// Call scrollTo() method of Javascript using window object.


js.executeScript("window.scrollTo(0, document.body.scrollHeight)"); // It will
scroll down until the end of the page .
}
}
In the preceding code, we have first launched the given URL in the Firefox
browser and then scrolled till the end (bottom) of the page. We have passed two-
argument values 0 (for horizontal scroll) and document.body.scrollHeight (for
vertical scroll) to the scrollTo() method.
The statement “document.body.scrollHeight” returns the complete height of the
body i.e web page.

How to Scroll Webpage Horizontal?

In this section, we will learn to scroll the web page horizontally.


Scenario to Automate:
1. Launch the web browser Firefox.
2. Open URL “https://selenium08.blogspot.com/2020/02/horizontal-scroll.html” on
the browser.
3. Locate a web element “Relationship” by using By.xpath.
4. Scroll page horizontally until the mentioned visible element on the current page.
Look at the source code related to the above scenario.
Program code 4:
package scrollUpandDown;
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;

public class ScrollHorizontal {


public static void main(String[] args)
{
// Create a web driver object.
WebDriver driver = new FirefoxDriver();

// Maximizing the window.


driver.manage().window().maximize();

// Launch the application.


String url = "https://selenium08.blogspot.com/2020/02/horizontal-scroll.html";
driver.get(url);
WebElement element = driver.findElement(By.xpath("//a[text() =
'Relationship']"));

// Create the JavascriptExecutor interface object by type casting of WebDriver


instance.
JavascriptExecutor js = (JavascriptExecutor)driver;

// Call scrollIntoView() method of Javascript using arguments[0].


js.executeScript("arguments[0].scrollIntoView();", element);
}
}
In the preceding code, we first launch the given URL in Firefox browser and then
scroll web page horizontally until the mentioned element is visible on the current
page.
Now run the above code and observe the output. When you will execute the above
script, you will get the following output as shown in the below screenshot.

You might also like