Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

chrome.windows.getAll() is undefined?

I want to write an extension (a session manager which has more features and eye candy than the ones already in the gallery) for google chrome / chromium.

But I can't get the following code to work:

function list_session() {
 var list = [];
 chrome.windows.getAll(
  {"populate" : true},

  function (window_list) {
   for(window in window_list) {
    list.concat(window.tabs);
   }
  }
 );
 console.log(list);
 return list;
}

It's a fairly simple example for the use of the google api, but instead of a list of tabs I get only 'undefined'values in return. Furthermore, the window list seems to be empty.

I'm currently running Chromium 7.0.517.44 (64615) under Ubuntu 10.10. I've tried the official chrome release from google as well with the same results.

API documentation can be found here: http://code.google.com/chrome/extensions/windows.html

phineas

like image 399
f4lco Avatar asked Nov 11 '10 17:11

f4lco


People also ask

How do I count the number of tabs in Chrome?

To find the number of tabs that are open, you could do something like: chrome. tabs. query({windowType:'normal'}, function(tabs) { console.

How do I open all tabs?

This looks like a down arrow, and it's located in the top right corner of the window. The Search Tabs popup window will now appear. An alternative way to get here is by using the keyboard shortcut: Shift + Command + A on Mac, or Control + Shift + A on PC.

How do I open a new window in Chrome?

To open a new window, use a keyboard shortcut: Windows & Linux: Ctrl + n. Mac: ⌘ + n.


1 Answers

Assuming you declared tabs permission in manifest, there are several problems with this code:

  • list_session() function will return empty list because you modify the list in a callback function, which could be called by chrome 15 minutes after your console.log(list); and return. You need to change your program structure to use callbacks instead.

  • concat method does not modify original array

  • in operator is not recommended to use to loop through an array as it might return not what you expect.

So I would write something like this:

function list_session(callback) {

    chrome.windows.getAll({populate : true}, function (window_list) {
        var list = [];
        for(var i=0;i<window_list.length;i++) {
            list = list.concat(window_list[i].tabs);
        }
        console.log(list);
        if(callback) {
            callback(list);
        }
    });
}

//usage
list_session(function(tab_list) {
    //use array of tabs
});
like image 97
serg Avatar answered Sep 30 '22 08:09

serg