我有一个外部页面,可以向我的Chrome扩展程序发送消息,后台脚本会获取并响应它。但是,我想首先处理function getID()
,然后才将响应(带有ID)发送回外部页面。
我已经尝试:设置$.when()
和setTimeout
等待getID。但没有任何作用,而且响应总是"未定义" ...
有没有等待函数执行,然后才将ID发送回外部页面?!
外部页面(发送消息)
var extID = "pncieomfimcmcbnbnogelnipdnkejmdf";
chrome.runtime.sendMessage(laserExtensionId, {getTargetData: true}, function(response) {
console.log(response);
});
后台脚本
var id;
function getID(){
$.get("url1", function( data1 ) {
//process data1 and use part of data1 on next get
$.get("url2", function( data2 ) {
//process data2 and use part of data2 on next get
$.get("url3", function( data3 ) {
//process data3 and return
return id;
});
});
});
}
chrome.runtime.onMessageExternal.addListener(
function(request, sender, sendResponse) {
getID();
sendResponse({user: id});
});
答案 0 :(得分:2)
你cannot return something from asynchronous functions。请在继续之前阅读该问题。
您需要在最后一次回调中调用sendResponse(id)
。此外,您通过从处理程序返回true
来need to inform Chrome that you will be doing that asynchronously。
function getID(callback){
$.get("url1", function( data1 ) {
//process data1 and use part of data1 on next get
$.get("url2", function( data2 ) {
//process data2 and use part of data2 on next get
$.get("url3", function( data3 ) {
//process data3 and pass the result to callback
callback(id);
});
});
});
}
chrome.runtime.onMessageExternal.addListener(function(request, sender, sendResponse) {
getID(function(id) {
// Will be called asynchronously from getID()
sendResponse({user: id});
});
return true; // Tell Chrome we need sendResponse asynchronously
});