How to execute JavaScript in Selenium WebDriver

Below code snippet shows you how to execute a JavaScript in Selenium WebDriver.


	WebDriver driver = new ChromeDriver();

	if (driver instanceof JavascriptExecutor) {
		((JavascriptExecutor) driver).executeScript("alert('hello world');");
	}

1. WebDriver Example

In this example, it uses WebDriver to load “google.com”, and executes a simple alert () later.

JavaScriptExample.java

package com.mkyong.test;

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", 
		"/Users/mkyong/Downloads/chromedriver");
		
	ChromeOptions options = new ChromeOptions();
	options.addArguments("window-size=1024,768");

	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('hello world');");
	}
		
  }
}

Output

js-selenium

References

  1. Selenium – WebDriver JavaDoc
  2. Selenium – JavascriptExecutor JavaDoc

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
ndroock1
Guest
ndroock1

Thank you! Saved me so much time.

prabhu pandi
Guest
prabhu pandi

Hi ,
How to print the value inside the alert.
For an example:
i want to print a value of ‘i’ with in the alert message. Is it possible?
My output should be like ‘The value of i is 10’ by using alert

Krushna
Guest
Krushna

Hi. Thank you for above information.It help us lot.
Now my query is that my script won’t work when i change the script language to JAVA instead of Java script. I know that web driver is compatible with javascript only, But is there any other way to use JAVA language instead of Java script? It throws ERROR – jmeter.JMeter: Uncaught exception: java.lang.NoClassDefFoundError: org/openqa/selenium/os/Kernel32 and browser closed immediately

Do we have to add enable or disable code line in Web Driver Sampler ?
Please reply soon.
Thanks

Jonathan Makuc
Guest
Jonathan Makuc

Also, not so obvious is that if you need to recover some javascript value to you code, you need to add a “return” to your javascript command.

For example: $driver->executeScript(‘return JSON.stringify(window.myData)’);

Since the Webdriver executes your code inside a javascript function in the target browser, you have to explicit the return instruction in order to recieve the data.

Very nice to extract window variables data :)

shubh
Guest
shubh

Hello, thanks for your knowledge sharing …while using above instruction I am getting “org.openqa.selenium.UnhandledAlertException: Modal dialog present: hello world

Build info: version: ‘2.39.0’, revision: ‘ff23eac’, time: ‘2013-12-16 16:12:12’…

any suggestion ?

Khaja
Guest
Khaja

Shubh, try giving Thread.sleep to debug the issue, may be the alert pop up is taking sometime to show up and thus driver is throwing this exception.

ratee bhatt
Guest
ratee bhatt

Hi Subh you just need swicth to the Alert window

driver.switchToAlert().accept();

Thanks

veodo
Guest
veodo

And HtmlUnitDriver !!!!! ??????

Sanket Paropate
Guest
Sanket Paropate

Hi, I am using Selenium Java and I have multiple Javascripts in a method. I want to wait for each Javascript to complete before the next script begins. Is there a way to do it?