Part 8: Usages Of Javascripts In Selenium: How To Scroll Web Page In Selenium WebDriver Using Javascript

Hello Folks,

In last post, we learnt about methods of Javascript which are used to scroll a web page. In this post, we will see usage of those methods in selenium webdriver.

Scroll web page using scrollTo method:

Selenium webdriver provides an inbuilt method called executeScript to execute any javascript command. We will use same methods to execute scrollTo commands.

Syntax:

window.scrollTo(0,300);

Kindly notice here I am using “window” not “document”. There are difference between window and document in javascript.  Let’s learn that as well:

Difference between window and document in javascript:

“window” and “document” are object in javascript which are not same. When we launch a browser, what you see (excluding header , footer i.e. highlighted below) is “window” as below:

 

When you launch any URL in window, is called “document”.

Here we need to scroll window, so we need to call scroll methods on window object.

Java code:

When you will run above code, you will see window is scrolled vertically down thrice on interval of 2 seconds.

Scroll web page using scrollBy method:

We already know the major difference between scrollTo and scrolBy methods. We will see implementation below:

Javacode:

When you will run above code, you will see window is scrolled vertically down thrice on interval of 2 seconds.

Scroll web page using scroll method:

It will be same as scrollTo method. See example below:

Note: When you pass co-ordinates with negative sign, it will be scrolled up.

That’s it guys in this post. We will see some more interesting thing about scroll in up coming posts.

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappySelenium

Author: Amod Mahajan

My name is Amod Mahajan and I am an IT employee with 4+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went throw so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning