簡體   English   中英

Javascript 重定向並注入新頁面

[英]Javascript redirect and inject into the new page

我正在編寫一個基於彈出窗口的 web 擴展供我自己使用 它對我來說基本上是一項重復性的任務,檢查幾個網站的信息。

訪問站點的順序由彈出窗口控制。 為了能夠逐頁瀏覽 go,我希望擴展彈出窗口將瀏覽器 window 轉發到該站點並設置一個 onload 事件,以便在加載完整的 ZFC35FDC70D5FC69D2369883A82E 后返回通信。

相關的擴展代碼目前如下所示:

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。

如何改進此代碼?

使用 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