Executing WebDriver JavaScript from Java: An Enhanced Guide
The command mentioned in the question, ./go webdriverjs, is a shell command designed to set up and initialize the WebDriverJs environment in a specific folder. However, it's important to note that WebDriverJs is a language binding that enables JavaScript tests rather than running JavaScript snippets from Java.
To run JavaScript code within Java WebDriver, utilize the following approach:
<code class="java">WebDriver driver = new AnyDriverYouWant(); if (driver instanceof JavascriptExecutor) { ((JavascriptExecutor)driver).executeScript("yourScript();"); } else { throw new IllegalStateException("This driver does not support JavaScript!"); }</code>
Alternatively, consider:
<code class="java">WebDriver driver = new AnyDriverYouWant(); JavascriptExecutor js; if (driver instanceof JavascriptExecutor) { js = (JavascriptExecutor)driver; } // else throw... // later on... js.executeScript("return document.getElementById('someId');");</code>
The JavascriptExecutor offers extensive documentation and capabilities. In its executeScript() method, you can execute function calls, raw JS, return values, and pass complex arguments.
Examples:
<code class="java">js.executeScript("return document.getElementById('someId');");</code>
<code class="java">WebElement element = driver.findElement(By.anything("tada")); js.executeScript("arguments[0].style.border='3px solid red'", element);</code>
<code class="java">js.executeScript( "var inputs = document.getElementsByTagName('input');" + "for(var i = 0; i < inputs.length; i++) { " + " inputs[i].type = 'radio';" + "}" );</code>
The above is the detailed content of How do I Execute JavaScript code from Java WebDriver?. For more information, please follow other related articles on the PHP Chinese website!