2

I can get browser tabs using a match pattern

browser.tabs.query({ url: 'https://mozilla.org/*/b/*/' })

https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns

During an update event of a tab I can get the tab id and the url, but how do I test that the tab matches my original match pattern?

browser.tabs.onUpdated.addListener(event => {
    browser.tabs.get(event).then((tab) => {
        if (tab.status === 'complete') {
            if (?? tab.url matches 'https://mozilla.org/*/b/*/') {
                console.log("Do something")
            }
        }
    })
});
select
  • 2,513
  • 2
  • 25
  • 36
  • 1
    [How to use just asterisk wildcard when searching?](https://stackoverflow.com/a/41298497) and [other examples](https://www.google.com/search?q=javascript+convert+globbing+asterisk+to+regexp) – wOxxOm Sep 07 '18 at 16:34

2 Answers2

1

A simple self-written asterisk matcher would be:

function match(pattern, url) {
  pattern = pattern.split("/");
  url = url.split("/");
  
  while(url.length) {
   const p = pattern.shift();
   if(p !== url.shift() && p !== "*")
    return false;
  }
  return true;
}

console.log(
  match("https://example.com/*/test/", "https://example.com/a/test/"),
  match("https://example.com/*/test/", "https://example.com/a/b/")
);
     
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • 1
    Thanks I was more hoping to know if there is a matcher somewhere exposed in the browser API since it is apparently used by the query function. I will however use this if there are no other answers coming in. – select Sep 07 '18 at 16:45
0

I think you can still use browser.tabs.query({ url: 'https://mozilla.org/*/b/*/' }) and see if your tab is among the tabs returned by the query.

dnovikov
  • 1
  • 1