Javascript executor is used to execute javascript from selenium. Actions which need to be performed forcibly can be performed using javascript executor. For example selenium not able to click on particular web element due to disable state of it but our requirement is to click on that element. In this case we can use JavascriptExecutor.
Javascript executor should not be used if operation on webelement can be performed using selenium. For instance if element is clickable by driver.findElement(“Locator”).click(); then we should not use JavaScriptExecutor.
Most of the time JavaScriptExecutor is used for scrolling into particular x and y location. And clicking on disabled element.
Syntax of javascript executor:
1 2 |
<span style="font-size: 20px;">JavascriptExecutor javascript = (JavascriptExecutor)driver; javascript.executeScript("Script need to be executed");</span> |
Example: Below code opens www.mundrisoft.com and it scrolls to 50,1500 location.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<span style="font-size: 20px;">import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.Test; public class JavaScriptExecutor { @Test public void Scroll() { WebDriver driver= new FirefoxDriver(); JavascriptExecutor javascript = (JavascriptExecutor)driver; driver.get("www.mundrisoft.com"); driver.manage().window().maximize(); javascript .executeScript("window.scrollBy(50,1500)"); } }</span> |