Back

Technologies:

javascriptjavascript
avatar
Tolerim
12 days ago

How can I use filtering to extract only the URLs from a list of Chrome tabs that match a given list of URLs?

My goal is to create a javascript code that filters specific Chrome tabs based on a list of specified URLs. The code should only return the tabs that match the input list.

Initially, I attempted to use a combination of links. Here is an example:

let urlLists = ['youtube.com', 'cnn.com']
chrome.tabs.query({ "url": urlLists.includes(p => `*://${p}/*`) }, (tabs) => {
    tabs.forEach((tab) => {
          console.log('tab.id: ',tab.id, 'tab.url:', tab.url);
}
However, this code did not work as intended. Do you have any suggestions for easier or alternate methods to achieve the same result? Note that I have all necessary permissions, and The following code outputs all the tabs:

chrome.tabs.query({}, (tabs) => {
        tabs.forEach((tab) => {
          console.log('tab.id: ',tab.id, 'tab.url:', tab.url);
        })
    })
Answers(2)
avatar
Vogi
11 days ago
Verified Answer
You can use the following code to filter specific Chrome tabs based on a list of specified URLs:
let urlLists = ['youtube.com', 'cnn.com'];
chrome.tabs.query({ url: urlLists.map(p => `*://${p}/*`) }, (tabs) => {
    tabs.forEach((tab) => {
          console.log('tab.id: ',tab.id, 'tab.url:', tab.url);
    });
});
The above code should only return the tabs that match the input list. The urlLists.map(p => *://${p}/*) part of the code maps each URL in the list to a pattern that matches all URLs that start with http:// or https:// and end with the URL in the list. This pattern is then used to filter tabs using the chrome.tabs.query() method. I hope this helps! Let me know if you have any other questions.

Sources

filter from chrome tabs all urls that match list of given urlsIs there way to query multiple urls using chrome.tabstabs.query () - Mozilla | MDN
avatar
Tolerim
12 days ago
The issue with the provided code is that the url query parameter of chrome.tabs.query expects a string or an array of strings that define the pattern for the URLs that we want to retrieve. In the given code, urlLists.includes(p => *://${p}/*) returns a boolean, not a pattern string. Therefore, we need to modify the code to create an array of pattern strings from the given input list and pass it to chrome.tabs.query. Here's an updated code example that should work as expected:
let urlLists = ['youtube.com', 'cnn.com'];
let urlPatterns = urlLists.map(url => `*://${url}/*`);
chrome.tabs.query({ url: urlPatterns }, tabs => {
  tabs.forEach(tab => {
    console.log(`tab.id: ${tab.id}, tab.url: ${tab.url}`);
  });
});
In this code example, we create an array of pattern strings by using Array.map to add the necessary prefixes and suffixes to each URL. Then we pass this array as the url query parameter to chrome.tabs.query. Lastly, we iterate through the retrieved tabs and log their IDs and URLs to the console.
;