JavaScript Execution through Selenium WebDriver – Scroll Down Operation

September 24, 2016

JavaScript is a programming language of HTML which is used to program the behaviour of web pages.

JavaScript Executor:

Selenium WebDriver provides support to inject any JavaScript on a browser. JavaScriptExecutor is an interface which is used to execute JavaScript through Selenium WebDriver. It has two methods “executeScript” & “executeAsyncScript”  to run JavaScript.

Let us consider an example “Scroll Down Operation” using Selenium WebDriver:

Refer below code:

In the above code, first we have defined a string variable “jsCommand” and another variable “jsEngine” of type javaScriptExecutor. jsCommand is initialised with the JavaScript to be executed, here in this example it is “window.scrollTo(<x-cordinate>, <y-cordinate>)” and jsEngine is used to run the command.

x and y coordinates are integer values, and their value is in pixels.

Practical Scenarios: Scroll down through a page after a product search on an ecommerce site:

Scenario:

  1. Open any browser of your choice say “Chrome.”
  2. Navigate to “http://www.ebay.in”.
  3. Search for a product say, “Apple watches” and select the category as “Watches” and click on Search button.
  4. A search operation is performed, and products are displayed on the page.
  5. Now scroll down to each product one by one and fetch its details.

Fetching the list using XPath locator

Refer the code below:

This scenario is an extension of a scenario we saw earlier while learning “Working with Dropdown”You can refer to this tutorial for the explanation of first four steps. Let us focus on 5th step here. To scroll down to each product first, fetch the location (i.e. x and y coordinates) of each product (WebElement) one by one and then call scroll down method.

getLocation().x; – this will return x coordinate on the screen.

getLocation().y; – this will return y coordinate on the screen.

Both the above, integer values are then passed as an argument in the window.scrollTo(int x, int y) method and is iterated over a List which contains all the products as a WebElement using enhanced for loop.

scrollTo is the same method that we saw earlier in this article.

By getText() method, we can fetch the details of all the products.

Above example can be considered as a reference to execute any JavaScript scenario, the only thing which changes is jsCommand. Rest the code will remain same.

For any questions, queries or comments feel free to write us at support@qatechhub.com or saurabh@qatechub.com. Happy Learning 🙂

Saurabh

About the Author

Saurabh

Follow Saurabh:

Leave a Comment: