A lot of times, you might encounter some scenarios that cannot be performed using regular Selenium WebDriver command. In this cases, using JavaScript commands can prove to be extremely useful. That’s why I compiled a list with 7 of the most useful JS commands that can help you in your Selenium tests:

1 – Scrolling to the bottom of the page

The JS method for scrolling is scrollTo. To make Selenium scroll down to the very bottom of the page, you need to use the webpage’s height (document.body.scrollHeight) – no need to use its absolute value:


2 – Scrolling to the top of the page

As you may have expected, this is done using the same method, but what we want to do is scroll the negative height of the webpage:


3 – Scrolling to a specific element

To achieve this, you must first identify the web element using the correct locator. Let’s say it’s stored in a variable called “myElement”. What our code will do is to scroll until myElement is visible, using the scrollIntoView method:


4 – Clicking on an element using JavaScript

Just like before, the first thing we have to do is find the element. After that, clicking on it is quite easy:


This one can be particularly useful when we try to avoid Selenium exceptions such as elementNotInteractableException or ElementClickInterceptedException.

5 – Refreshing the browser 

If you don’t want to use the driver.navigate().refresh()  Selenium command, you can replace it with this JavaScript executor:


Basically this tells the browser to go back 0 pages.

6 – Going back X number of pages

Yeap, just replace the 0 from the previous line of code with the number of Back actions you want to perform:


This line of code with take you back 3 pages.

7 – Testing sessionStorage

You can also use JavaScript executor to set items in the session storage, or get items, like below:


So these are some common JavaScript commands that can come to our aid when Selenium alone doesn’t provide the needed behavior. What are your thoughts on this? Leave a comment to let us know if you would add any other commands to the list.