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;

public class JsAlertCreation {

	public static void main(String[] args) throws InterruptedException 
		// inform selenium about driver path
		System.setProperty("", "D:\\browser-drivers\\chromedriver.exe");
		// instantiate driver object
		WebDriver driver = new ChromeDriver();
		// launch aut
		//maximize the site
		// lets wait for some time
		// cast driver object
		JavascriptExecutor js = (JavascriptExecutor)driver;
		// create alert
		js.executeScript("alert('Welcome to Keren Automation');");
		// wait for some time
		// handle this alert
		driver.switchTo().alert().accept(); // click on "Ok" on alert box
		// wait for some time
		// quit browser



Some more use-cases of JavascriptExecutor are on the way 🙂