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

2 thoughts on “Part 8: Usages Of Javascripts In Selenium: How To Scroll Web Page In Selenium WebDriver Using Javascript”

  1. Hi Amod,
    I am only able execute Command1 and rest of the two commands throwing the following error while performing scroll action . Could you please explain.
    Error:Exception in thread “main” org.openqa.selenium.WebDriverException: unknown error: call function result missing ‘value’

Leave a Reply

Your email address will not be published. Required fields are marked *