WebDriver executeAsyncScript 与 executeScript [英] WebDriver executeAsyncScript vs executeScript
问题描述
executeAsyncScript 和 executeScript 有什么区别?我如何使用诸如 window.onload 之类的事件?我试过这样的事情
What is the difference between executeAsyncScript and executeScript? How can i use event such as window.onload? I tried something like this
((JavascriptExecutor) driver).executeAsyncScript("window.onload = function() {alert('Hello')}");
但是当然没用...所以如果有人知道它是如何工作的,请写一个例子
But of course it did not work... So if anyone knows how it works please write an example
推荐答案
(保持简单,正确.)
execteScript
和 executeAsyncScript
的相关区别是:
The relevant difference between execteScript
and executeAsyncScript
is this:
使用 executeAsyncScript
调用的函数将完成回调"作为最后一个参数,必须调用该参数以表示脚本已完成执行.
The function invoked with executeAsyncScript
takes a 'done callback' as the last argument, which must be called to signal that the script is done executing.
这允许它与仅在使用回调时完成"的代码一起使用 - 例如.setTimeout 或异步 XHR.如果在超时限制内未调用完成回调",则返回的承诺将被拒绝.
This allows it to be used with code that only 'finishes' when a callback is used - eg. setTimeout or asynchronous XHR. If the 'done callback' is not called within the timeout limits the returned promise will be rejected.
根据 webdriver.WebDriver.executeAsyncScript文档:
与使用 #executeScript 执行同步 JavaScript 不同,使用 [#executeAsyncScript] 执行的脚本必须通过调用提供的回调显式表示它们已完成.此回调将始终作为最后一个参数注入到执行的函数中..
Unlike executing synchronous JavaScript with #executeScript, scripts executed with [#executeAsyncScript] must explicitly signal they are finished by invoking the provided callback. This callback will always be injected into the executed function as the last argument..
也就是说,两个函数都会阻止 WebDriver 控制流,直到它们完成 - 要么在 executeScript
的代码末尾运行,要么在使用 executeAsyncScript
调用完成回调":名称中的async"表示所使用的信号机制,并不意味着/暗示 JavaScript 代码实际上是相对于 WebDriver 异步执行的.
That is, both functions block the WebDriver control flow until they complete - either running off the end of the code for executeScript
or when calling the 'done callback' with executeAsyncScript
: "async" in the name signifies the signal mechanism used and does not mean/imply that the JavaScript code is actually executed asynchronously with respect to the WebDriver.
这篇关于WebDriver executeAsyncScript 与 executeScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!