我正在为我自己的私人用途编写一个基于弹出窗口的 Web 扩展。它基本上对我来说是一项重复性的任务,即检查几个网站的信息。
访问站点的顺序由弹出窗口控制。为了能够逐页浏览页面,我希望扩展弹出窗口将浏览器窗口转发到该站点并设置一个 onload 事件,以便在加载完整的 html 后返回通信。
相关的扩展代码目前如下所示:
function inject(jscode)
{
browser.tabs.executeScript(null, {code: jscode});
}
...
...
...
// next_url contains the url string of the next website to be visited
// stop contains a bool to decide if more actions will happen
if( next_url != '')
{
inject("window.location.assign('" + next_url + "');")
if( !stop )
{
await new Promise(resolve => setTimeout(resolve, 5000));
inject("browser.runtime.sendMessage({action: 'getSource', source: document.documentElement.innerHTML });")
}
}
如果所有相关的侦听器都已设置好,这样网站和扩展程序之间就可以进行通信,这将起作用。
但是,我不喜欢每次加载新网站时弹出窗口必须休眠 5 秒,以便将getSource
操作应用于完全加载的下一页而不是当前页面。到目前为止,我还没有找到一种方法来启动重定向并立即为要加载的 url 设置一个 onload 事件。
如何改进此代码?