Automated Tester


This content shows Simple View

September 2015

JavaScript Injection with Selenium

A useful trick we can deploy is injecting JavaScript to manipulate the browser or change values without specifying user interactions. Let’s see how:

internal void CloseActiveTab()
IJavaScriptExecutor js = Context.Driver as IJavaScriptExecutor;

This code is closing the active tab displayed. By Newing up the IJavaScriptExecutor interface, we can effectively send JavaScript commands directly to the browser console. As such, generally you can test this works by opening your browser console and running the JavaScript part of it, and if it errors you know it isn’t working and needs tweaking.

So we can specify what JavaScript to execute in the browser and then call it in our code, which can be useful and can also cut time off your tests if you can action one thing without having to action a whole bunch of user interactions to get there, it can serve as a great shortcut to get you to the element or item under test quickly.

How else can I use it?

Perhaps a  more common scenario or use of this might be to scroll down to the bottom of the page as this isn’t something Selenium can currently do on it’s own (to my knowledge!) but we can throw in some JavaScript to help us accomplish this:

public void ScrollToBottom()
IWebElement element = (IWebElement)((IJavaScriptExecutor)Context.Driver).ExecuteScript("javascript:window.scrollBy(0,document.body.scrollHeight-150)");

This will scroll to the bottom of the page you are currently on in your test if you have some odd things happening that may require it.

Generally speaking I try not to use JavaScript injection and stick to Selenium’s core capabilities but this can be a very useful work around where things don’t add up or where a reliable shortcut can be made.