A lot of times, you might encounter some scenarios that cannot be performed using the 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:

https://gist.github.com/ultimate-qa/87f75047e187862fedc25b93ba3757ab

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:

https://gist.github.com/ultimate-qa/2dfcc632e3fc55a7e5b2458dcad15778

3 – Scrolling to a specific element

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

https://gist.github.com/ultimate-qa/13415ac6cfd299b42d0d00bf1854dd71

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:

https://gist.github.com/ultimate-qa/d20088ab94270a6383c763770ce3929d

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:

https://gist.github.com/ultimate-qa/d64e2feadf5fc8b1f1ba83fa1053e101

This tells the browser to go back 0 pages.


6 – Going back X number of pages

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

https://gist.github.com/ultimate-qa/9d4840c7954ea3e1b8a06209da30b977

This line of code will 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:

https://gist.github.com/ultimate-qa/c1a3520fb93414aabe05cb71ad0c7310

These are some common JavaScript commands that can help 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.