Home >Java >javaTutorial >How can I execute JavaScript code within Java\'s Selenium WebDriver?
Using JavaScript with Selenium WebDriver Java
You are interested in utilizing JavaScript with WebDriver (Selenium 2) through Java.
Command Execution Location
The command you referred to, "$ ./go webdriverjs," should be executed from the directory where the WebDriverJs project is located.
Integrating JavaScript into WebDriver
However, note that WebDriverJs is a separate language binding for WebDriver, allowing test creation in JavaScript. To execute JavaScript within Java's WebDriver, follow these steps:
<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:
<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 executeScript() method accepts both function calls and plain JavaScript code. It offers the capability to return values and pass complex arguments, as demonstrated in these 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 can I execute JavaScript code within Java\'s Selenium WebDriver?. For more information, please follow other related articles on the PHP Chinese website!