gpt4 book ai didi

javascript - Chrome 应用程序执行脚本与 setTimeout,回调不等待

转载 作者:行者123 更新时间:2023-11-28 06:17:37 25 4
gpt4 key购买 nike

我正在开发 Chrome 应用程序,但遇到一个问题:

我首先注入(inject)一个file.js<webview> 打开的网站中.

在此file.js我有一个执行包含在 setTimeout 中的返回值的函数.

问题是当我使用 executeScript 调用该函数时,回调不会等待 setTimeout 结束,并返回 null .

有人可以告诉我我能做什么吗?谢谢!

(没有 setTimeout ,它返回预期值)

//content of file.js
function foo(){
setTimeout(function (){ return {key:"value"}; }, 5000);
}

//I inject the file.js in the website
webview.executeScript({file:"file.js"}, function(result){ console.log(result); });

//I call foo() in the website
webview.executeScript( {code:"foo();"}, function(result){ console.log(JSON.stringify(result)); });

最佳答案

executeScript 的回调将同步接收您运行的脚本的最后评估值。

您无法等待异步事件(setTimeout 就是)。

您最好的选择是使用 chrome.runtime.sendMessage 发回数据。 .

关于javascript - Chrome 应用程序执行脚本与 setTimeout,回调不等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35819288/

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