JavascriptExecutor is one of famous interfaces from the Selenium family, by using JavascriptExecutor, you can inject JavaScript calls in Selenium.
Today, I’ll show you a basic example use case of JavascriptExecutor, where one can create a custom alert (which is not available in the actual source) on any web page.
If you want to explore more details about JavascriptExecutor interface – Please click Here.
Example Program to Create custom Alert using JavascriptExecutor
package swdbasics; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class JsAlertCreation { public static void main(String[] args) throws InterruptedException { // inform selenium about driver path System.setProperty("webdriver.chrome.driver", "D:\\browser-drivers\\chromedriver.exe"); // instantiate driver object WebDriver driver = new ChromeDriver(); // launch aut driver.get("https://www.walmart.com/"); //maximize the site driver.manage().window().maximize(); // lets wait for some time Thread.sleep(3000); // cast driver object JavascriptExecutor js = (JavascriptExecutor)driver; // create alert js.executeScript("alert('Welcome to Keren Automation');"); // wait for some time Thread.sleep(4*1000); // handle this alert driver.switchTo().alert().accept(); // click on "Ok" on alert box // wait for some time Thread.sleep(2000); // quit browser driver.quit(); } }
Some more use-cases of JavascriptExecutor are on the way 🙂