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:
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
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:
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:
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:
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:
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.
As always, good stuff Nikolay!
Your posts are very useful with real life insight towards test automation. Keep sharing!
Thanks for this blog. It is very useful to understand selenium javascript commands. All the steps mentioned in the blogs makes it even more easy to understand the selenium javascript commands. I got to know about selenium testing course from Gayatri Mishra’s site, in which she provides free online selenium and other programming courses.
Do these work in C#? I didn’t find a OpenQA.Selenium.JavascriptExecutor to put into a using statement. Thank you.
Hello,
Yes, for C# you can use the IJavaScriptExecutor interface. The JavaScript code will be the same.
It should look like this:
IJavascriptExecutor jse = (IJavascriptExecutor) driver;