JavaScriptExecutor in Selenium
JavaScriptExecutor is one of the interfaces in selenium. The basic advantage of JavaScriptExecutor is it provides a way to execute JavaScript in Selenium Webdriver. Sometimes locators may not work, in that case JavaScriptExecutor will helps to interact with the web elements on the particular webpage. The reason behind this is; even selenium webdriver internally converts language bindings into its equivalent JavaScript and injects into the respective browser. JavaScriptExecutor is also very useful to identify and interact with the hidden and disabled elements on the webpage.
As JavaScriptExecutor is an interface so we can not create an object to this, for this we will type caste to driver object using below syntax:
JavascriptExecutor js = (JavascriptExecutor)driver; js.executeScript(javaScript, arguments);
Now we will see some of the examples below that how we can use JavaScriptExecutor to execute the JavaScript to interact with the web elements.
1. How to enter value into textbox:
JavascriptExecutor js = (JavascriptExecutor)driver; js.executeScript("document.getElementById('email').value='krishna@gmail.com'");
2. How to click a button:
JavascriptExecutor js = (JavascriptExecutor)driver; js.executeScript("document.querySelector('#enterimg').click()");
3. How to refresh a window:
JavascriptExecutor js = (JavascriptExecutor)driver; js.executeScript("history.go(0)");
4. How to get the text of a particular web element:
JavascriptExecutor js = (JavascriptExecutor)driver; String text = js.executeScript("return document.getElementById('btn2').innerHTML").toString(); System.out.println("WebElement Text is : "+ text);
5. How to get the title of the WebPage:
JavascriptExecutor js = (JavascriptExecutor)driver; String text = js.executeScript("return document.title").toString(); System.out.println("Page Title is : "+ text);
6. How to scroll vertically for certain pixels:
JavascriptExecutor js = (JavascriptExecutor)driver; js.executeScript("window.scrollBy(0,500)");
The above code vertically scrolls 500 pixels towards down.
7. How to scroll till the bottom of the web page:
JavascriptExecutor js = (JavascriptExecutor)driver; js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
8. How to scroll to a particular element:
JavascriptExecutor js = (JavascriptExecutor)driver; js.executeScript("document.querySelector('#countries').scrollIntoView()");
9. How to navigate back to page:
JavascriptExecutor js = (JavascriptExecutor)driver; js.executeScript("window.history.back()");
10. How to navigate to next page:
JavascriptExecutor js = (JavascriptExecutor)driver; js.executeScript("window.history.forward()");
This way we can JavaScriptExecutor to perform certain actions on a webpage if the normal selenium webdriver methods are not working.
Please watch YouTube video for better understanding.