Javascript 如何卸下‘;离开现场’;更新chrome extension中当前活动页面的url时弹出

Javascript 如何卸下‘;离开现场’;更新chrome extension中当前活动页面的url时弹出,javascript,google-chrome,browser,google-chrome-extension,Javascript,Google Chrome,Browser,Google Chrome Extension,我正在为谷歌日历开发一个chrome扩展。 事件发生后,我需要转到一个特定的url 所以我使用chrome.tabs.update(tabId,{url:'myurl'})来更新当前页面的url。 但在更新url时,请留下网站弹出窗口,这是浏览器的默认弹出窗口 在chrome extension中更新url时,请建议一种删除它的方法。理想情况下,这是由extensions API处理的,因此请启动。同时,我们可以使用下面列出的解决方法 最简单的方法是清除窗口。onbeforeunload 仅适用

我正在为谷歌日历开发一个chrome扩展。 事件发生后,我需要转到一个特定的url 所以我使用chrome.tabs.update(tabId,{url:'myurl'})来更新当前页面的url。 但在更新url时,请留下网站弹出窗口,这是浏览器的默认弹出窗口
在chrome extension中更新url时,请建议一种删除它的方法。理想情况下,这是由extensions API处理的,因此请启动。同时,我们可以使用下面列出的解决方法

最简单的方法是清除
窗口。onbeforeunload
仅适用于某些站点

扩展脚本(弹出或后台):

完全清除方法是在页面卸载之前注册
应该可以在任何地方使用,但缺点是它需要在扩展需要更新URL的所有URL上使用内容脚本。如果您已经在manifest.json中请求扩展的主要功能的这些主机权限,则这不是问题

manifest.json摘录:

"content_scripts": [{
  "matches": ["<all_urls>"],
  "js": ["content.js"],
  "run_at": "document_start"
}],
扩展脚本(弹出或后台):

"content_scripts": [{
  "matches": ["<all_urls>"],
  "js": ["content.js"],
  "run_at": "document_start"
}],
const pageEventId = chrome.runtime.id + Math.random;

runInPage(suppressor, pageEventId);

chrome.runtime.onMessage.addListener(msg => {
  if (msg === 'suppressBeforeUnload') {
    window.dispatchEvent(new Event(pageEventId));
  }
});

function runInPage(fn, ...args) {
  const script = document.createElement('script');
  script.textContent = `(${fn})(${JSON.stringify(args).slice(1, -1)})`;
  document.documentElement.appendChild(script);
  script.remove();
}

function suppressor(pageEventId) {
  let suppressBeforeUnload;
  window.addEventListener(pageEventId, () => {
    window.onbeforeunload = null;
    suppressBeforeUnload = true;
  });
  window.addEventListener('beforeunload', e => {
    if (suppressBeforeUnload) {
      e.stopImmediatePropagation();
    }
  });
}
chrome.tabs.sendMessage(tab.id, 'suppressBeforeUnload', () => {
  chrome.runtime.lastError;
  chrome.tabs.update({url: 'https://www.example.org/'});
});