JavascriptExecutor in Selenium Webdriver


Selenium Webdriver provides JavascriptExecutor interface to execute the Javascript in the browser window. this is one of good feature of selenium which allows you to execute client-side javascript.

So let’s create code for it. in this code we will cast the JavascriptExecutor to selenium webDriver.

import qeworks.javascriptexecutor

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

public class JavaScriptExample {
  public static void main(String[] args) {

	System.setProperty("", "drivers/chromedriver");
	ChromeOptions options = new ChromeOptions();
	DesiredCapabilities capabilities =;
	capabilities.setCapability(ChromeOptions.CAPABILITY, options);
	WebDriver driver = new ChromeDriver(capabilities);


	if (driver instanceof JavascriptExecutor) {
		((JavascriptExecutor) driver)
			.executeScript("alert('This Alert has been Injected by Selenium');");

Subscribe to Newsletter
Get Latest Posts, Articles and Learning Lessons on Software Testing and Test Automation
You can unsubscribe at any time

Comments are closed.