Execute JavaScript Using Selenium WebDriver


By: Amit Dabli | November 26, 2015

Selenium is one of the most popular and easy automated testing suites. Selenium is designed in a way to support and encourage automation testing of functional aspects of web based applications and a wide range of browsers and platforms.

JavaScript is the preferred language insideĀ in the browser to interact with HTML dom. This means that a Browser has JavaScript implemented in it and understands the JavaScript commands. You can disable it using browser options in your browser.

Webdrivers give you a method called Driver.executeScript which executes the JavaScript in context of the loaded browser page.

IJavaScriptExecutor interface available in selenium API. We can execute JavaScript code on the current web page opened by Selenium Webdriver using IJavaScriptExecutor

image

We can use an extension method to get the scripts object

image

JavaScript was also the language that was used by earlier Selenium versions, it is still used by Selenium webdriver to perform some actions. For e.g. Selenium has Xpath implemented in JavaScript for IE, to overcome the lack of Xpath engine in IE.

Example:

image

If you wish to start using WebDriver for the sake of testing, then that’s great. You should also keep in mind that browser automation doesn’t have to stop at testing, how about just automating a repetitive task?

This post has been viewed 2,810 times

One thought on “Execute JavaScript Using Selenium WebDriver

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>