1

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!

Vale2202
  • 43
  • 7
  • you should read https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith or https://stackoverflow.com/questions/646628/how-to-check-if-a-string-startswith-another-string – Lety Jul 29 '22 at 09:43
  • Does this answer your question? [How to check if a string "StartsWith" another string?](https://stackoverflow.com/questions/646628/how-to-check-if-a-string-startswith-another-string) – Lety Jul 29 '22 at 09:44
  • Instead of chrome.windows use `chrome.tabs.query({url: 'https://www.youtube.com/watch*'}, tabs => { console.log(tabs); })` – wOxxOm Jul 29 '22 at 10:01

2 Answers2

3

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!

Vale2202
  • 43
  • 7
0

Here u go

if (tab.url.contains("youtube") {
   console.log("youtube detected!")
}