JavascriptExecutor in Selenium Webdriver

77

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.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;

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

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

	driver.get("http://google.com/");

	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.