javascript is a framework code example
Example: when do you use javascript in your framework
Sometimes browser don’t react well against
selenium commands and we may face issues
while locating web elements. To overcome
such kind of situation, we use JavaScriptExecutor interface.
It provides mechanism to execute Javascript
through Selenium driver. It provides
“executescript” & “executeAsyncScript”
methods, to run JavaScript in the
context of the currently selected frame or window.
- Executed the JavaScript using Selenium WebDriver.
- Illustrated how to click on an element through
JavaScriptExecutor, if selenium fails to -
click on element due to some issue.
- Generated the 'Alert' window using JavaScriptExecutor.
- Navigated to the different page using JavaScriptExecutor.
- Scrolled down the window using JavaScriptExecutor.
- Fetched URL, title, and domain name using JavaScriptExecutor.
JavascriptExecutor js = (JavascriptExecutor)Driver.getDriver();
js.executeScript("script",arguments);
Script – The JavaScript to execute
Arguments – The arguments to the script(Optional). May be empty.
Returns – One of Boolean, Long, String, List, WebElement, or null.
Examples:
- js.executeScript("document.getElementById('someId');")==>works like driver.findElement("")
- js.executeScript("document.getElementById('someId').value='xxx';")==>works like .sendKeys("")
- String title=js.executeScript("return document.title;").toString()==>works like getTitle
- String URL = js.executeScript("return document.URL;").toString()==>works like getCurrentUrl
- js.executeScript("document.getElementById('someId').click();")==>works like findElement.click()
- WebElement loginButton=driver.findElement(By.xpath("//*[@id='next']"))==>pass to below line
js.executeScript("arguments[0].click();", loginButton)==>pass the loginButton into js.
- js.executeScript("scroll(0,600);")==>Scroll Down (not possible with Java) (600 is pixel number that you want to go down, It may be 1000, 800, 200 etc.)