Let's have a look at some examples of the things that we can do with the JavaScript executor that aren't really possible using the base Selenium API.
First of all, we will start off by getting the element text.
Wait a minute, element text? That's easy. You can use the existing Selenium API with the following code:
WebElement myElement = driver.findElement(By.id("foo")); String elementText = myElement.getText();
So, why would we want to use a JavaScript executor to find the text of an element?
Getting text is easy using the Selenium API, but only under certain conditions. The element that you are collecting the text from needs to be displayed. If Selenium thinks that the element from which you are collecting the text is not displayed, it will return an empty string. If you want to collect some text from a hidden element, you are out of luck. You will need to implement a way to do it with a JavaScript executor.
Why would you want to do this? Well, maybe you have a responsive website that shows different elements based on different resolutions. You may well want to check whether these two different elements are displaying the same text to the user. To do this, you will need to get the text of the visible and invisible elements so that you can compare them. Let's create a method to collect some hidden text for us:
private String getHiddenText(WebElement element) {
JavascriptExecutor js = (JavascriptExecutor)
((RemoteWebElement) element).getWrappedDriver();
return (String) js.executeScript("return arguments[0].text",
element);}
We have a bit of cleverness in this method. First of all, we took the element that we wanted to interact with and then extracted the driver object associated with it. We did this by casting the WebElement into a RemoteWebElement, which allowed us to use the getWrappedDriver() method. This removed the need to pass a driver object around the place all the time (this is something that happens a lot in some code bases).
Unfortunately, we get a base WebDriver object, not a RemoteWebDriver object, so we have to take this WebDriver object and cast it into a JavascriptExecutor object to gain the ability to invoke the .executeScript() method. Next, we execute the JavaScript snippet and pass in the original element as an argument. Finally, we take the response of the executeScript() call and cast it into a string that we can return as a result of the method.