从后台页面捕获所有选项卡的 onHistoryStateUpdated 事件

Catching onHistoryStateUpdated events for all tabs from a background page

我正试图在我的 WebExtensions 扩展中捕获 webNavigation.onHistoryStateUpdated using chrome.tabs

问题是,我只能为我创建的用于侦听来自 所有 其他选项卡的 onHistoryStateUpdated 事件的持久后台页面捕获 onHistoryStateUpdated 事件!

tabs.onUpdated 事件在后台页面上工作得很好,但 onHistoryStateUpdated 不行——这很重要,因为我必须捕捉浏览器 back/forward 事件——


manifest.json

{
  "manifest_version": 2,

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },

  "background": {
    "page": "background.html",
    "persistent": true
  },

  "permissions": [
    "tabs",
    "webNavigation"
  ]
}

background.js

// Works not... (i.e. is not fired)
chrome.webNavigation.onHistoryStateUpdated.addListener(function(details) {
    console.log("tabid", tabId);
});


// WORKS!
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {    
    console.log("Tab #" + tabId, " has its URL to: (" + changeInfo.status + ")");
    console.log("\t" + changeInfo.url);
});

两者Chrome documentation and the WebExtensions documentation explicitly state that the webNavigation.onHistoryStateUpdated event is fired when the history API都是用来改变地址栏中的URL。两者均未声明当用户单击 forwardback 按钮时触发事件。

如果您想确定导航是用户点击 forwardback 的结果,您需要听到 webNavigation.onCommitted MDN events. The information is available as the value "forward_back" being included in the transitionQualifiers MDN 数组。在这种情况下,transitionType 似乎仍然是浏览器最初导航到 URL 的方法。