PAGE 38: How To Execute JavaScript In Selenium WebDriver

Sometimes it is important to run JavaScript directly from the code to get any property of  Browser-BOM,  HTML-DOM  etc.

  • The Browser Object Model (BOM) allows JavaScript to "talk to" the browser. It includes Window, Navigator, Screen, History, Location etc.
  • With the HTML DOM, JavaScript can access and change all the elements of an HTML document. It includes Document, HTML, CSS, Elements etc.

We can execute JavaScript in 2 simple steps:

  • Cast the WebDriver instance to a  JavascriptExecutor
    JavascriptExecutor js = (JavascriptExecutor) driver;
  • Execute JavaScript
    js.executeScript("script for execution")

Example:


package com.example.tests;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class JavaScriptExecutionExample {
WebDriver driver;
@BeforeTest
public void setup(){
driver = new FirefoxDriver();
}
@Test
public void ExecuteJavaScript(){
driver.get("http://www.google.com/");
//// Cast WebDrier instance to a JavascriptExecutor
JavascriptExecutor js = (JavascriptExecutor) driver;
//// The readyState property returns the (loading) status of the current document: 'document.readyState'
System.out.println("Document state : "+js.executeScript("return document.readyState"));
//// Return the domain name of the server that loaded the document: 'document.domain;'
System.out.println("Domain : "+js.executeScript("return document.domain"));
//// The title property returns the title of the current document (the text inside the HTML title element): 'document.title'
System.out.println("Page Title : "+js.executeScript("return document.title"));
//// The URL property returns the full URL of the current document: 'document.URL'
System.out.println("URL : "+js.executeScript("return document.URL"));
//// Return the cookies associated with the current document: 'document.cookie'
System.out.println("Cookie : "+js.executeScript("return document.cookie"));
//// Returns the width of a window screen: 'screen.width'
System.out.println("Screen Width : "+js.executeScript("return screen.width"));
//// Return JavaScript Errors associated with the current window: 'window.jsErrors'
System.out.println("Windows js errors : "+js.executeScript("return window.jsErrors"));
}
@AfterTest
public void tearDown(){
driver.quit();
}
}

No comments:

About Me

My photo
Pune, Maharastra, India
You can reach me out at : jimmiamrit@gmail.com