Pages

Friday, 9 March 2012

How can I execute Javascript?

We can execute Javascript by casting the WebDriver instance to a JavascriptExecutor:

//Instantiate any WebDriver; Eg. Firefox
 WebDriver driver = new FirefoxDriver();
 driver.get("http://seleniumwebdriverfaq.tumblr.com/");
 //Casting the WebDriver instance to a JavascriptExecutor
 JavascriptExecutor js = (JavascriptExecutor) driver;
 //Execute the JavaScript - Eg. to get the page title
 js.executeScript("return document.title");
 //Print the out put
 System.out.println("Page title from Java script: "
      +js.executeScript("return document.title"));
 System.out.println("Page title from driver.getTitle() : "
      +driver.getTitle());
 //JUnit Assertion
 Assert.assertEquals(js.executeScript
    ("return document.title"),driver.getTitle());

1 comment: