JavaScript Executor in Selenium

As JavaScript Executor is an interface so we cannot 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='[email protected]'");

 

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 JavaScript Executor to perform certain actions on a webpage if the normal selenium webdriver methods are not working.

Leave a Reply

Your email address will not be published. Required fields are marked *