Friday, 3 October 2014

How To Execute JavaScript In Selenium WebDriver

Sometimes it is important to run JavaScript directly from the code to get any property of  Browser-BOM,  HTML-DOM  etc.
  • The Browser Object Model (BOM) allows JavaScript to "talk to" the browser. It includes Window, Navigator, Screen, History, Location etc.
  • With the HTML DOM, JavaScript can access and change all the elements of an HTML document. It includes Document, HTML, CSS, Elements etc.

We can execute JavaScript in 2 simple steps:

  1. Cast the WebDriver instance to a  JavascriptExecutor
    JavascriptExecutor js = (JavascriptExecutor) driver;
  2. Execute JavaScript
    js.executeScript("script for execution")

Example:


No comments:

Post a Comment