Collections:
JavascriptExecutor to Run JavaScript in Java
How to run JavaScript code on WebDriver with JavascriptExecutor in Java?
✍: FYIcenter.com
If you want run some client side JavaScript code in the same way
as JavaScript code embedded in the Web page source code,
you can use the JavascriptExecutor interface as describe below:
1. Load the Web page to a WebDriver object like (driver.get(url);).
2. Cast the WebDriver object to a JavascriptExecutor object like (executor = (JavascriptExecutor) driver;).
3. Execute any JavaScript code string by calling the executeScript() or executeAsyncScript() method on the JavascriptExecutor object.
Here is an example program that uses JavascriptExecutor to change the background color of the loaded Web page.
// JavascriptExecutorTest.java
// Copyright (c) FYIcenter.com
import org.openqa.selenium.*;
public class JavascriptExecutorTest {
public static void main(String[] args) {
WebDriver driver = WebDriverLoader.load(args[0]);
driver.get("http://sqa.fyicenter.com");
try {
Thread.sleep(3*1000);
String script = "document.body.style.backgroundColor=\"#ffeeee\";";
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript(script);
Thread.sleep(60*1000);
} catch (Exception e) {
}
driver.quit();
}
}
Compile and run the program, you will see that the background color of the Web page changes to pink in 3 seconds.
C:\fyicenter> javac -classpath \ .;\fyicenter\selenium\java\client-combined-3.141.59.jar \ JavascriptExecutorTest.java C:\fyicenter> java -classpath \ .;\fyicenter\selenium\java\client-combined-3.141.59.jar;\ \fyicenter\selenium\java\libs\guava-25.0-jre.jar;\ \fyicenter\selenium\java\libs\okhttp-3.11.0.jar;\ \fyicenter\selenium\java\libs\okio-1.14.0.jar;\ \fyicenter\selenium\java\libs\commons-exec-1.3.jar \ JavascriptExecutorTest Chrome
You can also try some other JavaScript code examples list below:
String script = "alert(\"Hello world!\")";
String script = "confirm(\"Hello world!\")";
⇒ Dump Elements with By.xpath() in Java
⇐ Submit Web Form with WebDriver in Java
2020-01-04, ∼2224🔥, 0💬
Popular Posts:
How to generate ISBN numbers? To help you to obtain some ISBN numbers for testing purpose, FYIcenter...
What are date and time test values? Date and time test values are frequently needed in testing date ...
Where to find tutorials on Apache JMeter test tool? I want to know how to use Apache JMeter. Here is...
How to validate Mod 10 (Luhn Algorithm) checksum? In order to help your programming or testing tasks...
How to perform UUDecode (Unix-to-Unix Decode)? UUEncode is Unix-to-Unix encoding used on Unix system...