應(yīng)用場(chǎng)景:網(wǎng)站嵌入 content_main.js文件 需要與background.js相互通信回調(diào)
//content_main.js
chrome.runtime.sendMessage({addurl:_url,adddata:data,msg:"contentRequest"}, function(response) {
if(response.status){
...
}else{
...
}
});
//background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.msg=="contentRequest"){
//ajax settimeout 等一系列異步操作時(shí)發(fā)現(xiàn)content_main response接不到回調(diào)值 undefined
ajax({
type:'post',
// contentType: 'application/x-www-form-urlencoded',
contentType: 'application/json; charset=utf-8',
url:request.addurl,
// data:{'documents':bibliographic_data},
data:request.adddata,
success:function(w){
if(w.code==200){
sendResponse({status:1,msg:"保存成功!"});
}else{
sendResponse({status:0,msg:"保存失敗判族,錯(cuò)誤代碼1001"});
}
return true;
},
error: function(xhr,info,e,){
sendResponse({status:0,msg:"保存失敗,錯(cuò)誤代碼1002"});
},
})
return true;// 原因在此 完美解決
}
});
注:使用嵌入式開(kāi)發(fā)有個(gè)弊端即在https網(wǎng)站嵌入發(fā)異步請(qǐng)求即在content_main中發(fā)后臺(tái)請(qǐng)求會(huì)若服務(wù)為http服務(wù)會(huì)發(fā)生請(qǐng)求被拒絕問(wèn)題践宴,上述案例也完美的解決該問(wèn)題德崭,僅供參考具體以實(shí)際開(kāi)發(fā)情況為主栗菜。