To run JavascriptExecutor we need to import the package:
import org.openqa.selenium.JavascriptExecutor;
1. To Perform click operation:
Syntax: JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement ele = driver.findElement(By.id("123"));
js.executeScript("arguments[0].click();" , ele);
//js.executeScript("Script", Arguments);
Syntax 2: JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementById('123').click();");
Example:
class JavaScript
{
public static void main(String[] args)
{
System.setProperty("webdriver.chrome.driver" , "path");
WebDriver driver = new ChromeDriver();
JavascriptExecutor js = (JavascriptExecutor) driver;
driver.get("https://testingcolleges.blogspot.com/p/testingform.html");
WebElement btn = driver.findElement(By.id("fem"));
js.executeScript("arguments[0].click();" , btn);
// instead of the above two lines we can also write the following line
//js.executeScript("document.getElementById('fem').click();");
}
}
2. To Perform value operation(just like sendKeys()): Fill an element with text in a webpage by executing javaScript.
Syntax: JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement ele = driver.findElement(By.id("123"));
js.executeScript("arguments[0].value='Hello';" , ele);
//js.executeScript("Script", Arguments);
Syntax 2: JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementById('123').value='Hello';");
Example:
class JavaScript
{
public static void main(String[] args)
{
System.setProperty("webdriver.chrome.driver" , "path");
WebDriver driver = new ChromeDriver();
JavascriptExecutor js = (JavascriptExecutor) driver;
driver.get("https://testingcolleges.blogspot.com/p/testingform.html");
WebElement FirstName = driver.findElement(By.name("fname"));
js.executeScript("arguments[0].value='Testing';" , FirstName);
// instead of the above two lines we can also write the following line
//js.executeScript("document.getElementByName('fname')[0].value='Testing';");
}
}
3. Creating an Alert box using JavaScript:
Syntax: JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("alert('your message');");
Example:
class JavaScript
{
public static void main(String[] args)
{
System.setProperty("webdriver.chrome.driver" , "path");
WebDriver driver = new ChromeDriver();
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("alert('welcome to Testing Colleges ! ...');");
}
}
No comments:
Post a Comment