Skizit
Skizit

Reputation: 44842

Chrome-Extension: iterate through all tabs?

How would I iterate through all tabs a user has open and then check if they have a particular HTML item with id = 'item'?

Upvotes: 38

Views: 42995

Answers (4)

Nicolas
Nicolas

Reputation: 225

Edit July 2022:

This answer was originally written for MV3 users. If you're looking for a MV2 answer, see above. Otherwise, this answer will work perfectly fine with MV3.

Original answer

chrome.tabs.query is the function you're looking for. You can pass in parameters to a object to filter the tabs. In your case, you want to iterate over all the open tabs. Here's two versions of the code you're looking for:

Asynchronous callback version

chrome.tabs.query({}, function(tabs) {
  tabs.forEach(function (tab) {
    // do whatever you want with the tab
  });
});

Promise version

var tabs = await chrome.tabs.query({});
tabs.forEach(function (tab) {
  // do whatever you want with the tab
});

In both cases, the parameter tab is a Tab.

Upvotes: 10

Sindar
Sindar

Reputation: 10839

You can make it like this:

chrome.tabs.getAllInWindow(null, function(tabs){
  for (var i = 0; i < tabs.length; i++) {
    chrome.tabs.sendRequest(tabs[i].id, { action: "xxx" });                         
  }
});

After that to look after your item, if you can make it like this :

document.getElementById('item')

Don't forget that you can't manipulate the HTML by using the "background page" So the first code snip is for the background page, and the second have to be on a content script ;)

Upvotes: 24

Emeeus
Emeeus

Reputation: 5250

This is a not deprecated vanilla way (may 2019):

chrome.tabs.query({}, function(tabs){
        tabs.forEach(tb => {
            chrome.tabs.sendMessage(tb.id, { action: "xxx" });
        });
    });

Upvotes: 2

Golden Flying Broom
Golden Flying Broom

Reputation: 863

It appears this method has been deprecated in favor of chrome.tabs.query:

http://developer.chrome.com/extensions/tabs.html#method-query

So now you'd want to do:

chrome.tabs.query({}, function(tabs) { /* blah */ } );

Passing an empty queryInfo parameter would return all of the tabs.

Upvotes: 80

Related Questions