My Thoughts: February 2013

Saturday, February 2

Executing javascript using Selenium WebDriver

Using webdriver sometimes we need to run javascript code dircetly from our script.

In one of the previous post we have discussed how to break catcha on webpage . To break captcha we need to run javascript code directly from our script .So it is important to know how to run javacript code using WebDriver. Here are the steps:

1.Cast the WebDrier instance to a  JavascriptExecutor
WebDriver driver;
JavascriptExecutor js = (JavascriptExecutor) driver;
2.Use executeScript method to run the script
js.executeScript("return document.title");
Here is the sample script using TestNG.
import java.util.ArrayList;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Reporter;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class ExecuteJavascript {
	
 WebDriver driver;

 @BeforeTest
 public void start(){
  driver = new FirefoxDriver();
 }
 
 @Test
 public void javaScriptExec(){
  
  driver.get("http://duckduckgo.com/");
  JavascriptExecutor js=(JavascriptExecutor) driver;
  
  String readyState=(String)js.executeScript("return document.readyState");
  System.out.println("readyState  : "+readyState);

  String title=(String)js.executeScript("return document.title");
  System.out.println("title  : "+title);
		  
  String domain=(String)js.executeScript("return document.domain");
  System.out.println("domain  : "+domain);
		  
  
  String lastModified=(String)js.executeScript("return document.lastModified");
  System.out.println("lastModified  : "+lastModified);
		  
  String URL=(String)js.executeScript("return document.URL");
  System.out.println("Full URL  : "+URL);

 String error=(String) ((JavascriptExecutor) driver).executeScript("return window.jsErrors");
  System.out.println("Windows js errors  :   "+error);
		   
   }

@AfterTest
 public void stop(){
 driver.quit();
 }

}
If you run the above program then the output will come like below :

readyState  : complete
title  : DuckDuckGo
domain  : duckduckgo.com
lastModified  : 02/02/2013 13:11:42
Full URL  : https://duckduckgo.com/
Windows js errors  :   null

Reference :

http://code.google.com/p/selenium/wiki/WebDriverJs#Getting_Started
http://code.google.com/p/selenium/wiki/FrequentlyAskedQuestions#Q:_How_do_I_execute_Javascript_directly?
http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/JavascriptExecutor.html