11/25/17

JavaScriptExecutor in Selenium WebDriver



JavaScriptExecutor in Selenium WebDriver:
In general, we do click on an element using click() method in Selenium.

Sometimes web controls don’t react well against selenium commands and we may face issues with the above statement (click()). To overcome such kind of situation, we use JavaScriptExecutor interface.


It provides mechanism to execute Javascript through Selenium driver. It provides “executescript” & “executeAsyncScript” methods, to run JavaScript in the context of the currently selected frame or window.

There is no need to write separate script to execute JavaScript within the browser using Selenium WebDriver script. Just use predefined interface named ‘Java Script Executor’. We need to import the below package in the script.

Package:

import org.openqa.selenium.JavascriptExecutor;

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

 To type Text in Selenium WebDriver without using sendKeys() method
js.executeScript("document.getElementById('Email').value='pavan123456@gmail.com';");
To click a Button in Selenium WebDriver using JavaScript executor.
           WebElement loginButton=driver.findElement(By.name("login"));
           js.executeScript("arguments[0].click();", loginButton);

To handle Checkbox
js.executeScript("document.getElementById('chkbox1').checked=false;");

To generate Alert Pop window in selenium
js.executeScript("alert('Welcome To pavantestingtools.com');");

To refresh browser window using Javascript
js.executeScript("history.go(0)");

To get innertext of the entire webpage in Selenium
String iText =  js.executeScript("return document.documentElement.innerText;").toString();
System.out.println(iText);

 To get the Title of our webpage
String title =  js.executeScript("return document.title;").toString();
System.out.println(title);

To get the URL of a webpage
String utl =  js.executeScript("return document.URL;").toString();
System.out.println(url);

To perform Scroll on application 
//Vertical scroll - down by 500  pixels
js.executeScript("window.scrollBy(0,500)");
// for scrolling till the bottom of the page we can use the code like
//js.executeScript("window.scrollBy(0,document.body.scrollHeight)");

To click on a SubMenu which is only visible on mouse hover on Menu
 js.executeScript("$('ul.menus.menu-secondary.sf-js-enabled.sub-menu li').hover()");

To navigate to different page using Javascript
js.executeScript("window.location = 'https://www.pavantestingtools.com");




0 comments:

Post a Comment