如何将 URL 与 chrome 扩展名中的片段标识符匹配?

How to match URL with fragment identifier in chrome extension?

我正在尝试使用以下代码来区分 vSphere 登录页面和工作页面的URL。

vSphere 登录页面的 URL 如下所示:

https://0.0.0.0/vsphere-client/?csp

登录后的工作页面如下所示:

https://0.0.0.0/vsphere-client/?csp#extensionId%3Dvsphere.core.controlcenter.shortcutsView

所以,我想在登录页面显示我的扩展程序图标,而不是在工作页面显示。

我尝试了以下代码,但它没有用,我的意思是图标在这两个 URL 上可用:

chrome.runtime.onInstalled.addListener(function () {
  chrome.declarativeContent.onPageChanged.removeRules(undefined, function () {
    chrome.declarativeContent.onPageChanged.addRules([
      {
        conditions: [
          new chrome.declarativeContent.PageStateMatcher({
            pageUrl: { querySuffix: 'csp' },
          })
        ],
        actions: [new chrome.declarativeContent.ShowPageAction()]
      }
    ]);
  });
});

对于行:

pageUrl: { querySuffix: 'csp' },

我也试过 $ 到 URL 末尾的正则表达式,但没有成功:

pageUrl: { urlMatches: 'csp$' },

我知道片段标识符 # 之后的部分不会在 pageUrl: { xxx }, 中处理,请参考 https://developer.chrome.com/extensions/events#property-UrlFilter-hostEquals

它说:

Matches if the URL (without fragment identifier) matches a specified regular expression. Port numbers are stripped from the URL if they match the default port number. The regular expressions use the RE2 syntax.

所以,也许 pageUrl 将登录页面和工作页面视为相同 URL。

这里有什么方法可以识别这两个 URL 吗?

谢谢!

恐怕 declarativeContent API 根本无法完成您的要求。

您应该探索其他选项,例如注入 content script 并从那里检查页面状态;然后,您可以将后台脚本发送给 enable/disable 页面操作。

作为一种不同的方法,您可以处理 webNavigation API 事件以跟踪 URL 更改并相应地更新页面操作可见性。

请注意,当页面在这些状态之间转换时,可能不会发生实际导航(而是发生历史状态更改);在这种情况下,您需要明确隐藏您的页面操作。