0

The question may be stupid, I've just started learning chrome API. But I really have become exhausted when looking for an answer. Here we are:

When I'm using this construction, everything is A-OK:

chrome.tabs.executeScript(tabID, { file: "jquery.js" }, function() {
    chrome.tabs.executeScript(tabID, { file: "script.js" }, function(res)   { 
        alert(res); // I can use this result inside this block
    });
});

The matter is that I'd like to encapsulate this code into a function like this:

function aFunction( tabID )
{
    chrome.tabs.executeScript(tabID, { file: "jquery.js" }, function() {
        chrome.tabs.executeScript(tabID, { file: "script.js" }, function(res)   { 
            return res;
        });
    });
}

Then I use the function this way:

alert(aFunction(tabID));

The message provided by this alert-instruction is "undefined". I tried many ways to write the function, but I constantly get "undefined" as a returned result.

Hope there is a way to implament what I'd like to.

Thanks in advance.

4

1 回答 1

1

Chrome extension APIs are asynchronous, so if you wrap them inside of a function, that wrapping function can't synchronously return a value based on an asynchronous result. The wrapping function must declare its return value before the Chrome API callback functions begin.

You can do this:

function aFunction( tabID, callback )
{
    chrome.tabs.executeScript(tabID, { file: "jquery.js" }, function() {
        chrome.tabs.executeScript(tabID, { file: "script.js" }, function(res)   { 
            callback(res);
        });
    });
}

Instead of returning res, you can pass in a callback function to aFunction that runs when executeScript terminates.

aFunction(1234, function(resultArg) {
    alert("if you're seeing this, the inner executeScript finished");
    alert("it has result" + resultArg);
});

The inner executeScript executes the callback(res) call, which invokes the function passed into aFunction with res as its first argument.

Remember that any code that requires the res value must be placed inside the callback. Any code outside of the callback has no guarantee (or in fact has a negative guarantee) that the executeScript callback has yet resolved.

于 2013-10-16T13:21:44.150 回答