2013-10-16 38 views
0

这个问题可能很愚蠢,我刚开始学习chrome API。但是在寻找答案时我真的很疲惫。在这里,我们有:将chrome API操作封装成函数

当我使用这样的结构,一切都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 
    }); 
}); 

的问题是,我想封装这个代码到这样的功能:

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

然后我使用该函数是这样的:

alert(aFunction(tabID)); 

通过此警报指令所提供的信息是“理解过程罚款”。我尝试了很多方法来编写这个函数,但是我经常把“undefined”作为返回结果。

希望有一种方法可以植入我想要的东西。

在此先感谢。

+1

这是一个异步调用!它不会像那样工作。原始函数调用在executeScript行运行之前返回。由于函数中没有返回值,因此您会得到未定义的值。 – epascarello

+0

是的,我明白这一点),但我认为把回归指令放到一个我们真正得到回应的块中就能解决问题。 –

+0

@ITcrusader它不起作用,因为'aFunction'必须在执行'executeScript'回调之前声明它的返回值并终止*。因此,'executeScript'不可能影响'aFunction'的返回值。 – apsillers

回答

1

Chrome扩展API是异步的,因此如果将它们包装在函数内部,则该包装函数无法基于异步结果同步返回值。在开始Chrome API回调函数之前,包装函数必须声明其返回值

你可以这样做:

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

,而不是返回res的,你可以在回调函数aFunction运行时executeScript终止通过。

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

executeScript执行callback(res)呼叫,这将调用传递到aFunctionres作为它的第一个参数的函数。

请记住,任何代码即需要res值必须放在回调。回调之外的任何代码都不能保证(或事实上有负面保证)executeScript回调尚未解决。

+0

谢谢!它确实解决了我的功能分解问题=) –