A pragmatic approach to QA and OPS

Playing With JavaScript and JavaScript Executor

JavaScript is a language that was created by Brendon Eich, to have a way to interact dynamically with the HTML DOM. In today’s world, JavaScript is one of the most popular and widely used language to create dynamic websites. If you don’t know what JavaScript is, you should probably head over to this page and read about it.

The earlier versions of Selenium used JavaScript in a good way, and though the current versions don’t use it in such a tightly coupled way, we have more sophisticated and better methods in order to deal and use the power of JavaScript.

JavaScript In Selenium

We have two main functions that we are going to talk about that help us in dealing with the JavaScript things in Selenium.

  • JavaScriptExecutor interface

JavaScriptExecutor is an interface that provides us the mechanism to execute JavaScript through the selenium driver.

  • ExecuteScript method

This is the method that actually executes the JavaScript command that you pass inside this method as an argument.

These two concepts are explained in details in this link. I would like people visiting to read this link first because this would give a fair understanding of how to use both these components in our forthcoming scripts.

E.g.- You can use the executeScript method for scrolling down the page.

driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

  • ExcecuteAsyncScript method

There is another method provided by Selenium API, under the JavaScriptExecutor interface is the ExecuteAsyncScript method.  This method is also used to run JS commands but only those who methods that  ‘finishes’  only when a callback is used – eg. setTimeout or asynchronous XHR.

The function invoked with executeAsyncScript takes a ‘done callback’ as the last argument, which must be called to signal that the script is done executing.

E.G- You can use the executeAsyncScript method for setting the timeout

("window.setTimeout(arguments[arguments.length − 1], 800);");

You can read about the detailed difference between these two methods in this awesome link.

However, please note that async in the name doesn’t mean that the methods described in the ExecuteAsyncScript will run async of the Selenium code. It is imperative to know that , both functions block the WebDriver control flow until they complete – either running off the end of the code for executeScript or when calling the ‘done callback’ with executeAsyncScript.

%d bloggers like this: