Based on your previous questions, I suppose you want to run JavaScript snippets from Java's WebDriver
.
(根据您之前的问题,我想您想要从Java的WebDriver
运行JavaScript代码段。)
Please correct me if I'm wrong.(如果我错了,请纠正我。)
The WebDriverJs
is actually "just" another WebDriver
language binding (you can write your tests in Java, C#, Ruby, Python, JS and possibly even more languages as of now).
(WebDriverJs
实际上是“只是”另一种WebDriver
语言绑定(您可以用Java,C#,Ruby,Python,JS编写测试,甚至可能还有更多语言)。)
This one, particularly, is JavaScript, and allows you therefore to write tests in JavaScript.(特别是这一个是JavaScript,因此允许您用JavaScript编写测试。)
If you want to run JavaScript code in Java WebDriver
, do this instead:
(如果要在Java WebDriver
运行JavaScript代码,请执行以下操作:)
WebDriver driver = new AnyDriverYouWant();
if (driver instanceof JavascriptExecutor) {
((JavascriptExecutor)driver).executeScript("yourScript();");
} else {
throw new IllegalStateException("This driver does not support JavaScript!");
}
I like to do this, also:
(我也喜欢这样做:)
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 find more documentation on this here, in the documenation , or, preferably, in the JavaDocs of JavascriptExecutor
.
(您可以在此处,文档中找到更多相关文档,或者最好在JavascriptExecutor
的JavaDocs中找到 。)
The executeScript()
takes function calls and raw JS, too.
(executeScript()
接受函数调用和原始JS。)
You can return
a value from it and you can pass lots of complicated arguments to it, some random examples:(你可以从它return
一个值,你可以传递许多复杂的参数,一些随机的例子:)
// returns the right WebElement // it's the same as driver.findElement(By.id("someId")) js.executeScript("return document.getElementById('someId');");
// draws a border around WebElement WebElement element = driver.findElement(By.anything("tada")); js.executeScript("arguments[0].style.border='3px solid red'", element);
// changes 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';" + "}" );
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…