How to match URL with fragment identifier in chrome extension?

843 views Asked by At

I'm trying to use the following code to distinguish the URL of vSphere login page and the working page.

The URL of vSphere login page looks like this:

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

And the working page after login looks like this:

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

So, I'd like to show my extension icon at the login page, not show at working page.

I tried the following code but it did not work, I mean the icon is available on these two URLs:

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()]
      }
    ]);
  });
});

For the line:

pageUrl: { querySuffix: 'csp' },

I also tried the regex to the end of URL by $ and did not work:

pageUrl: { urlMatches: 'csp$' },

I know the part after fragment identifier # will not be process in pageUrl: { xxx }, refer to https://developer.chrome.com/extensions/events#property-UrlFilter-hostEquals.

It says:

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.

So, maybe the pageUrl regards the login page and working page the same URL.

Is there any way to identify these two URLs here?

Thanks!

1

There are 1 answers

0
Xan On BEST ANSWER

I'm afraid that declarativeContent API is simply unable to do what you're asking.

You should explore alternative options, such as injecting a content script and checking the page's state from there; you can then message your background script to enable/disable the page action.

As a different approach, you can process webNavigation API events to track URL changes and update the page action visibility accordingly.

Note that it's possible that no actual navigation occurs as the page transitions between those states (history state changes happen instead); in that case you'll need to explicitly hide your page action.