Sunday, April 26, 2015

JavaScript Executor

JavaScriptExecutor its an Interface in Selenium WebDriver. It provides way to inject JavaScript in browser through WebDriver.

We have two methods in it :- 

1. executeScript(java.lang.String script, java.lang.Object... args).
2. executeAsyncScript(java.lang.String script, java.lang.Object... args).

Now, the question is why we need it and how we use it in our code ?

First, many times in our code we need to scroll page, click on particular element if failed with driver click, prompt user with some text on browser, to get the JS errors on page and many more. Basically it enhances coding capabilities and enables tester to  achieve end results. 

Below are the some examples using JavaScriptExecutor:- 

This is the syntax :- 

JavascriptExecutor js = (JavascriptExecutor) driver;   
js.executeScript(Script,Arguments); 

Examples:- 


Alert:- 
JavascriptExecutor js = (JavascriptExecutor)driver;
Js.executeScript("alert('hello');");

To get the title of the page:- 
js.executeScript("return document.title");
need to cast in String and it will print the title of the page like this:-
String title=(String)js.executeScript("return document.title"); 
System.Out.Print(title);

To get the date and time of the last modification:- 
js.executeScript("return document.lastModified"); 

To get the errors on page:- 
String errorsOnPage =(String) js.executeScript("return window.jsErrors"); 

To get the URL :- 
String URL=(String)js.executeScript("return document.URL");  

To click on element:- 
js.executeScript("arguments[0].click();", element);

another way to move to particular element :- 
js.executeScript("var evt = document.createEvent('MouseEvents');" + "evt.initMouseEvent('click',true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0,null);" + "arguments[0].dispatchEvent(evt);",element);

To refresh the browser:- 
js.executeScript("history.go(0)");

To scroll vertically/horizontally by 100 pixels :- 
Vertical scroll -> js.executeScript("window.scrollBy(0,100)");
horizontal scroll ->  js.executeScript("window.scrollBy(100,0)");

To navigate to other page :- 
js.executeScript("window.location = 'http://www.google.com'");

To inspect and send some values:- 
js.executeScript("document.getElementById('xyz').value='xyz'");