Search code examples
javascriptgoogle-chrome-extension

How to detect if a url is opened in a chrome extension


In my chrome extension, I want to detect if a url is opened and to get its ID. The url is "https://www.youtube.com/*" (the * is the variable part of the url) and I would like to detect, when the popup's button is clicked, if the url is opened.

I already tried this code:

chrome.windows.getAll({populate:true},function(windows){
  windows.forEach(function(window){
    window.tabs.forEach(function(tab){
      //for each url check if the url is "https://www.youtube.com/*"
      if(tab.url === "https://www.youtube.com/*") {
       console.log("youtube detected!")
      }
    });
  });
});

but, if the url is like "https://www.youtube.com/watch?v=dQw4w9WgXcQ", it won't log "youtube detected!" (so it won't work). I think the problem is in the "/*" of the url but I don't know how to detect url's variable parts after the "https://www.youtube.com/". How could I solve this problem? Thanks!


Solution

  • Thanks everyone, this works:

    chrome.windows.getAll({populate:true},function(windows){
      windows.forEach(function(window){
        window.tabs.forEach(function(tab){
    
          //for each url check if the url is "https://www.youtube.com/*"
          if(tab.url.startsWith("https://www.youtube.com/")) {
           console.log("youtube detected!");
          }
    
        });
      });
    });
    

    I also found this way:

    chrome.tabs.query({url: "https://www.youtube.com/*"}, tabs => {
      console.log("youtube detected!");
      //let url = tabs[0].url; use this to get the url
    });
    

    if you have a better solution, please let me know about that!