Javascript is a compelling language to interact with DOM. So it would make sense to use Javascript to run in the browser using Selenium whenever there is no other way to work on a particular element using Selenium.
JavascriptExecutor is an interface.
By creating object JavascriptExecutor jse=(JavascriptExecutor)driver;
we can use method executeScript to execute anything in the browser using javascript.
Firstly, some of the basic things like a scroll, get URL, Title can be performed using javascript with the following code.
window.scrollBy(0,400); // x, y --> x is for horizontal scroll. y is for vertical scroll. And if you pass negative value it scrolls in other direction.
document.URL; // get URL of current browser
document.domain; // get domain of browser
document.title; // get title of the browser page.
Now, this code we can execute in selenium using.
JavascriptExecutor jse=(JavascriptExecutor)driver;
jse.executeScript("window.scrollBy(0,400);");
it would scroll down by 400 pixels from the current position.
You could also javascript returning some data such as in boolean, long, String, WebElement and using in your selenium code.
Eg:
String currentURL= jse.executeScript(""return document.URL").toString();
Similarly, you can write javascript to work on any element for that matter and call it in Selenium.
Another approach you can use with JavascriptExecutor is to use elements created to execute in Javascript.
Eg:
WebElement button=driver.findElement(By.name("Insert"));
button.click();
jse.executeScript("arguments[0].click();",button);