automationScript

How to use JavaScriptExecutor in Selenium WebDriver

Selenium commands with JavaScriptExecutor.

To run JavaScript commands with Selenium automation scripts, we have to use JavaScriptExecutor in Selenium which comes separately as well as part of Selenium WebDriver but both do the same thing. 
Within the WebDriver, it is called by command ExecuteScript and the independent one is called JavaScriptExecutor
You can do any operation you want to do in the browser with the help of JavaScript if normal WebDriver commands are not working as expected.
Please see below some examples of common JavaScript commands.
JavascriptExecutor js = (JavascriptExecutor)driver;
Js.executeScript("alert('hello world');");

How to click an element using JavaScriptExecutor in selenium

JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", element);

How to Refresh Browser using JavaScriptExecutor

JavascriptExecutor js = (JavascriptExecutor)driver;

driver.executeScript("history.go(0)");

How to get InnerText of a Webpage using JavaScriptExecutor

JavascriptExecutor js =(JavascriptExecutor)driver;

string sText =  js.executeScript("return document.documentElement.innerText;").toString();

How to get title of a WebPage using JavaScriptExecutor

JavascriptExecutor js =(JavascriptExecutor)driver;

string sText =  js.executeScript("return document.documentElement.innerText;").toString();

How to Scroll Page using JavaScriptExecutor in selenium

JavascriptExecutor js =JavascriptExecutor)driver;
  //Vertical scroll - down by 150  pixels
js.executeScript("window.scrollBy(0,150)");

How to get count of links on page using JavaScriptExecutor

JavascriptExecutor js =JavascriptExecutor)driver;
long linkCount = (Long) js.executeScript("var links = document.getElementsByTagName('A'); return links.length");

How to set value in an element using JavaScriptExecutor

JavascriptExecutor js =JavascriptExecutor)driver;
js.executeScript("document.getElementByID('name').value = arguments[0]","John");

How to highlight an element on the page during runtime using JavaScriptExecutor

Subscribe for updates