0

I'm getting a somewhat unexpected result from running the following script (in my Chrome Extension):

        chrome.windows.getAll({populate: true}, function(wnds)
        {
            for(var w = 0; w < wnds.length; w++)
            {
                var tabs = wnds[w].tabs;

                for(var t = 0; t < tabs.length; t++)
                {
                    var tab = tabs[t];
                    var tabUrl = tab.url;

                    try
                    {
                        chrome.tabs.executeScript(tab.id, {
                            file: "content.js",
                            allFrames: true,
                            matchAboutBlank: true
                        }, function(arrRes)
                        {
                            if(chrome.runtime.lastError)
                            {
                                console.error("INJ ERR: " + chrome.runtime.lastError.message);
                            }
                            else
                            {
                                console.log("INJ OK: " + tabUrl);
                            }
                        });
                    }
                    catch(e)
                    {
                    }
                }
            }
        });

when the script runs by itself I get the following in the console log screen:

enter image description here

but when I step through it with a debugger, it outputs something like this (or correct info for each page):

enter image description here

I'm obviously expecting the second result. So what am I doing wrong?

c00000fd
  • 20,994
  • 29
  • 177
  • 400

1 Answers1

1

You need to create a closure for each invocation of executeScript so you get the right value of tabUrl each time your callback function is invoked. The way your code is right now, all invocations will use the last value of tabUrl. One way to fix that would be:

    chrome.windows.getAll({populate: true}, function(wnds)
    {
        for(var w = 0; w < wnds.length; w++)
        {
            var tabs = wnds[w].tabs;

            for(var t = 0; t < tabs.length; t++)
            (function()
            {
                var tab = tabs[t];
                var tabUrl = tab.url;

                try
                {
                    chrome.tabs.executeScript(tab.id, {
                        file: "content.js"
                    }, function(arrRes)
                    {
                        if(chrome.runtime.lastError)
                        {
                            console.error("INJ ERR: " + chrome.runtime.lastError.message);
                        }
                        else
                        {
                            console.log("INJ OK: " + tabUrl);
                        }
                    });
                }
                catch(e)
                {
                }
            })();
        }
    });
rsanchez
  • 14,467
  • 1
  • 35
  • 46