JavaScript execution in WebDriver, JavascriptExecutor Interface, executeScript

public interface JavascriptExecutor :

The interface indicates the driver can execute JavaScript.
===========================================================
////The below example type selenium in google and click search

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.firefox.FirefoxDriver;

public class google_js
{
  public static void main(String[] args) throws Exception
  {
   FirefoxDriver fd=new FirefoxDriver();
   fd.get("http://www.google.com");
   Thread.sleep(5000);
         ///create object for JavascriptExecutor interface
   JavascriptExecutor js=(JavascriptExecutor)fd;
         ////get the element in the page and perform the required event
   js.executeScript("window.document.getElementById('gbqfq').value='selenium' ");
   js.executeScript("window.document.getElementById('gbqfb').click() ");
  }
}
============================================================
executeScript method :
Executes JavaScript in the the current selected frame or window.

If the script has a return value (i.e. if the script contains a return statement), then the following steps will be taken:

    For an HTML element, this method returns a WebElement
    For a decimal, a Double is returned
    For a non-decimal number, a Long is returned
    For a boolean, a Boolean is returned
    For all other cases, a String is returned.
    For an array, return a List with each object following the rules above. We support nested lists.
    Unless the value is null or there is no return value, in which null is returned

Arguments must be a number, a boolean, a String, WebElement, or a List of any combination of the above. An exception will be thrown if the arguments do not meet these criteria. The arguments will be made available to the JavaScript via the "arguments" magic variable, as if the function were called via "Function.apply"

Parameters:
    script - The JavaScript to execute
    args - The arguments to the script. May be empty
Returns:
    One of Boolean, Long, String, List or WebElement. Or null.

Comments