Wednesday, 3 July 2013

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
  1. WebDriver driver;  
  2. JavascriptExecutor js = (JavascriptExecutor) driver;  
2.Use executeScript method to run the script
  1. js.executeScript("return document.title");  
Here is the sample script using TestNG.
  1. import java.util.ArrayList;  
  2. import org.openqa.selenium.JavascriptExecutor;  
  3. import org.openqa.selenium.WebDriver;  
  4. import org.openqa.selenium.firefox.FirefoxDriver;  
  5. import org.testng.Reporter;  
  6. import org.testng.annotations.AfterTest;  
  7. import org.testng.annotations.BeforeTest;  
  8. import org.testng.annotations.Test;  
  9.   
  10. public class ExecuteJavascript {  
  11.       
  12.  WebDriver driver;  
  13.   
  14.  @BeforeTest  
  15.  public void start(){  
  16.   driver = new FirefoxDriver();  
  17.  }  
  18.    
  19.  @Test  
  20.  public void javaScriptExec(){  
  21.     
  22.   driver.get("http://duckduckgo.com/");  
  23.   JavascriptExecutor js=(JavascriptExecutor) driver;  
  24.     
  25.   String readyState=(String)js.executeScript("return document.readyState");  
  26.   System.out.println("readyState  : "+readyState);  
  27.   
  28.   String title=(String)js.executeScript("return document.title");  
  29.   System.out.println("title  : "+title);  
  30.             
  31.   String domain=(String)js.executeScript("return document.domain");  
  32.   System.out.println("domain  : "+domain);  
  33.             
  34.     
  35.   String lastModified=(String)js.executeScript("return document.lastModified");  
  36.   System.out.println("lastModified  : "+lastModified);  
  37.             
  38.   String URL=(String)js.executeScript("return document.URL");  
  39.   System.out.println("Full URL  : "+URL);  
  40.   
  41.  String error=(String) ((JavascriptExecutor) driver).executeScript("return window.jsErrors");  
  42.   System.out.println("Windows js errors  :   "+error);  
  43.              
  44.    }  
  45.   
  46. @AfterTest  
  47.  public void stop(){  
  48.  driver.quit();  
  49.  }  
  50.   
  51. }  
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

No comments:

Post a Comment