It seems like you're interested in executing JavaScript snippets using Java's WebDriver
. If I'm mistaken, please feel free to correct me.
The WebDriverJs
is essentially just another language binding for WebDriver
(you can write tests in various languages such as Java, C#, Ruby, Python, JS, and more). This specific one focuses on JavaScript, allowing you to create tests in that language.
If your goal is to run JavaScript code in Java through WebDriver
, follow this approach instead:
WebDriver driver = new AnyDriverYouWant();
if (driver instanceof JavascriptExecutor) {
((JavascriptExecutor)driver).executeScript("yourScript();");
} else {
throw new IllegalStateException("This driver does not support JavaScript!");
}
I also prefer the following method:
WebDriver driver = new AnyDriverYouWant();
JavascriptExecutor js;
if (driver instanceof JavascriptExecutor) {
js = (JavascriptExecutor)driver;
} // else throw...
// later on...
js.executeScript("return document.getElementById('someId');");
You can explore further documentation regarding this topic here, in the documentation, or, ideally, in the JavaDocs of JavascriptExecutor
.
The executeScript()
function supports function calls and raw JS code. It allows you to return
a value from it and pass complex arguments. Here are some examples:
1.
// returns the correct WebElement
// equivalent to driver.findElement(By.id("someId"))
js.executeScript("return document.getElementById('someId');");
-
// adds a border around a WebElement
WebElement element = driver.findElement(By.whatever("hello"));
js.executeScript("arguments[0].style.border='3px solid red'", element);
-
// converts all input elements on the page to radio buttons
js.executeScript(
"var inputs = document.getElementsByTagName('input');" +
"for(var i = 0; i < inputs.length; i++) { " +
" inputs[i].type = 'radio';" +
"}" );