Chrome 扩展以在任何地方打开特定 url 选项卡时显示上下文菜单

Chrome extension to show a contextual menu if a specific url tab is open anywhere

我写了一个上下文 menu-based Chrome 扩展。它允许我将收音机正在播放的音乐曲目保存为收藏夹。我希望此菜单项仅在打开具有特定匹配 URL 的无线电播放器的选项卡时才可用 anywhere(不必 activecurrentWindow)。显然,当这个广播播放器关闭时,菜单项也应该从菜单中隐藏。

菜单项上的

documentUrlPatterns 不会那样工作 - 它只会在匹配页面上显示该项目。我的目标是无需先切换到单选标签即可保存收藏夹。

我的猜测是我应该用玩家的url听tabs.onCreated/onUpdated/onRemoved。或许也到onReplaced。但是有没有更好、更“懒惰”的方法来实现呢?

使用webNavigation API with event filters for the URL. Event filters are registered inside Chrome itself so it wakes up the background script with "persistent": false only when the filter is matching. Note that filters use different syntax, not like normal matching patterns, as you can see in the example below and in each event's documentation.

const filters = {
  url: [{
    hostEquals: 'www.example.com',
    queryContains: 'foo=bar',
  }]
};
chrome.webNavigation.onCompleted.addListener(onNavigation, filters);
chrome.webNavigation.onHistoryStateUpdated.addListener(onNavigation, filters);
chrome.webNavigation.onReferenceFragmentUpdated.addListener(onNavigation, filters);

function onNavigation(info) {
  console.log(info);
  // modify your context menu here
}

manifest.json当然应该有"permissions": ["webNavigation"]