My Thoughts: Executing javascript using Selenium WebDriver

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


8 comments:

  1. THANKS BRO.. IT HELPED ME A LOT..

    ReplyDelete
  2. FYI, if you want to see additional tips on javascript execution, like the types of javascript you could execute that is really useful for Selenium automation, see these posts:

    http://autumnator.wordpress.com/2013/02/09/javascript-is-your-ally-for-selenium-webdriver/

    http://autumnator.wordpress.com/2013/02/21/selenium-automation-with-execution-of-custom-site-specific-javascript/

    ReplyDelete
  3. The line checking 'readyState' - either this is a brilliant and simple solution for checking if the document is "ready for scraping" (how come I haven't thought of that?), or there is something missing here (since I have not encountered this in any other forum, including on StackOverflow).
    Thanks

    ReplyDelete
  4. This piece of writing offers clear idea in support of the new
    viewers of blogging, that truly how to do blogging and site-building.|

    My weblog program pit 2014 (http://2014pitprogram.com.pl)

    ReplyDelete
  5. HI,

    My requirement is that i need to test a javascript function in a HTML page with parameters.

    function CallMe(a,b){
    alert("Hello");
    var c = a + b;
    return c;
    }

    Now in java i used selenium to execute the above mentioned function.

    JavascriptExecutor executor = (JavascriptExecutor)driver;
    Object result = null;
    try{
    result = executor.executeScript("return CallMe(5,4)");
    driver.switchTo().alert().accept();
    }catch(NoAlertPresentException ex){
    System.out.println("Alert not found");
    }
    System.out.println(result.toString());



    Now the output of the program is the text of the alert box i.e "Hello", but if i run the above program without the alert box in javascript then the result comes as "9".
    Can you help me in this regard why my rest of the javascript code is not tested?


    Thanks in Advance

    ReplyDelete
  6. Hi Suhird ,

    I am not sure how exactly you are calling an exterbnal script file from your java code. But I find the below code online , which will help you .

    engine.eval("function add (a, b) {c = a + b; return c; }");
    Invocable jsInvoke = (Invocable) engine;
    Object result1 = jsInvoke.invokeFunction("add", new Object[] { 10, 5 });
    System.out.println(result1);





    When I run the program , output is coming fine i.e 15.

    ReplyDelete
  7. hi

    i am trying to execute this javascript but it shows error that javascript is not resolved eventhough i tried the methos which you wrote

    javascript:void(window.open(%22%22,%22dp_debugger%22,%22width=600,height=600,location=0,menubar=0,status=1,toolbar=0,resizable=1,scrollbars=1%22).document.write(%22%3Cscript%20language=\%22JavaScript\%22%20id=dbg%20src=\%22https://www.adobetag.com/d1/digitalpulsedebugger/live/DPD.js\%22%3E%3C/%22+%22script%3E%22))

    if you will save this as a bookmark and execute it will open a pop up i need to extract the element of this pop up window. please help me

    ReplyDelete
  8. Hi Vinay,

    I tried to break the js into below two lines. And it is working in google console:

    top=window.open("","dp_debugger","width=600,height=600,location=0,menubar=0,status=1,toolbar=0,resizable=1,scrollbars=1")
    top.document.writeln("")



    I hope it works for you now also.

    ReplyDelete