gpt4 book ai didi

javascript - 自己线程中的 Selenium 异步脚本会阻止其他脚本

转载 作者:太空宇宙 更新时间:2023-11-04 12:38:42 25 4
gpt4 key购买 nike

我有这样的场景:

不同的脚本必须在浏览器中执行。其中之一是将消息从一个浏览器发送到另一个浏览器(WebRTC)。我想测量每个操作的延迟,特别是发送消息的延迟。

为了实现这一目标,我为每个 selenium 驱动程序创建了一个自己的线程,该线程正在执行脚本。此外,我还创建了另一个线程,该线程正在等待消息从其他浏览器到达观察到的浏览器。等待消息的线程执行如下异步脚本:

String message = (String) ((JavascriptExecutor) driver).executeAsyncScript(
"window.receivedMessage = function(message_id){" +
"arguments[arguments.length - 1](message_id);" +
"}");

如您所见,如果浏览器收到消息,我正在等待调用的回调。

不幸的是,这会阻止在浏览器中注册此异步脚本后我想要执行的所有其他脚本(无论是 .executeScript() 还是 .executeAsyncScript() )。

是否有人知道如何不断等待消息到达并使用网络驱动程序执行其他脚本?

编辑

顺便说一句:忙碌的等待不应该是解决方案。我更喜欢一种以某种方式通知 selenium 操作已完成的方法,而无需不断轮询驱动程序的结果。

最佳答案

一种方法是将消息存储在全局变量中,并在执行其他脚本后处理它们。这是一个例子:

JavascriptExecutor js = (JavascriptExecutor)driver;
driver.manage().timeouts().setScriptTimeout(20, TimeUnit.SECONDS);

// set a listener for the messages
js.executeScript(
"window._asyncResult = []; " +
"window.receivedMessage = function(message_id) { " +
" window._asyncResult.push(message_id); " +
"}; " );

// send a message asynchroniously every second
js.executeScript(
"window._asyncTimer = setInterval(function(){ " +
" window.receivedMessage(Math.random()); " +
"}, 1000); " );

// wait for 5 messages and return the list
List messages = (ArrayList)js.executeAsyncScript(
"var callback = arguments[arguments.length - 1]; " +
"(function fn(){ " +
" if(window._asyncResult.length > 5) { " +
" clearInterval(window._asyncTimer); " +
" return callback(window._asyncResult); " +
" } " +
" setTimeout(fn, 30); " +
"})(); " );

关于javascript - 自己线程中的 Selenium 异步脚本会阻止其他脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37052804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com