Execute JavaScript Using Selenium WebDriver

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?

Write a comment
Cancel Reply
  • Admin November 30, 2015, 10:41 am
    test
    reply