简体   繁体   English

Javascript 重定向并注入新页面

[英]Javascript redirect and inject into the new page

I'm writing a popup-based web extension for my own private use .我正在编写一个基于弹出窗口的 web 扩展供我自己使用 It basically does a repetitive task for me of checking several websites for information.它对我来说基本上是一项重复性的任务,检查几个网站的信息。

The order of sites visited is controlled by the popup.访问站点的顺序由弹出窗口控制。 In order to be able to go through the pages one by one I'd like the extension popup to forward the browser window to that site and set up an onload-event to communicate back once the full html has been loaded.为了能够逐页浏览 go,我希望扩展弹出窗口将浏览器 window 转发到该站点并设置一个 onload 事件,以便在加载完整的 ZFC35FDC70D5FC69D2369883A82E 后返回通信。

The relevant extension code currently looks like this:相关的扩展代码目前如下所示:

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 });")
    }
}

This will work if all relevant listeners have been set up so that communication can happen between the website and the extension.如果所有相关的侦听器都已设置好,这样网站和扩展程序之间就可以进行通信,这将起作用。

However, I don't like how the popup has to sleep for 5 seconds each time it loads a new website so that the getSource action gets applied to the fully loaded next page rather than the current one.但是,我不喜欢每次加载新网站时弹出窗口必须休眠 5 秒,以便将getSource操作应用于完全加载的下一页而不是当前页面。 So far I haven't found a way to initiate a redirect and instantly setup an onload-event for that to be loaded url.到目前为止,我还没有找到一种方法来启动重定向并立即设置一个加载事件以加载 url。

How could this code be improved?如何改进此代码?

Use browser.tabs.update to change the URL and browser.tabs.onUpdated to detect the exact moment the page has loaded.使用 browser.tabs.update 更改 URL 和browser.tabs.onUpdated以检测页面加载的确切时间。

(async () => {
  await goToUrl(nextUrl);
  const [html] = await browser.tabs.executeScript({
    code: 'document.documentElement.innerHTML',
  });
})();

async function goToUrl(url) {
  const {id: tabId} = await browser.tabs.update({url});
  return new Promise(resolve => {
    browser.tabs.onUpdated.addListener(function onUpdated(updId, info) {
      if (updId === tabId && info.status === 'complete') {
        browser.tabs.onUpdated.removeListener(onUpdated);
        resolve();
      }
    }, {tabId});
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM