Wednesday, 29 January 2014

Integrate JS with Selenium | Basics

JavaScript make it simpler when Selenium fail to execute certain cases. Here we start with basic exercises using JavascriptExecutor.


1| Alert Msg

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("alert('Hai! This is an Alert msg');");



2| Get Title

driver.get("http://google.co.in/");
JavascriptExecutor js = (JavascriptExecutor) driver;
String title = (String) js.executeScript("return document.title");
System.out.println("title  : " + title);
OUTPUT | title  : Google 


3| Get Domain name

driver.get("http://google.co.in/");
JavascriptExecutor js = (JavascriptExecutor) driver;
String domain = (String) js.executeScript("return document.domain");
System.out.println("domain  : " + domain);
OUTPUT | domain  : www.google.co.in


4| Get URL

driver.get("http://google.co.in/");
JavascriptExecutor js = (JavascriptExecutor) driver;
String URL = (String) js.executeScript("return document.URL");
System.out.println("Full URL  : " + URL);
OUTPUT | Full URL  : https://www.google.co.in/


5| Get Attribute | Text

driver.get("http://google.co.in/");
Object exampleDiv = ((JavascriptExecutor) driver).executeScript("return document.getElementById('main');");
String name = ((WebElement) exampleDiv).getAttribute("class");
System.out.println(name);
OUTPUT | content


6| Last Modified

driver.get("http://google.co.in/");
JavascriptExecutor js = (JavascriptExecutor) driver;
String lastModified = (String) js.executeScript("return document.lastModified");
System.out.println("lastModified  : " + lastModified);
OUTPUT | lastModified  : 01/29/2014 14:56:46


7| Ready state

driver.get("http://google.co.in/");
JavascriptExecutor js = (JavascriptExecutor) driver;
String readyState = (String) js.executeScript("return document.readyState");
System.out.println("readyState  : " + readyState);
OUTPUT | readyState  : complete


8| Click()

WebElement element = driver.findElement(By.id("Value"));
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();", element);
OR |
WebElement element = driver.findElement(By.id("Value"));
trigger("arguments[0].click();", element);

public void trigger(String script, WebElement element) {
((JavascriptExecutor) driver).executeScript(script, element);
}
OR |
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.document.getElementById('Value').click()");

3 comments: