我正在向后台脚本发送消息并在监听器中接收数据,
在内容脚本中”
function sendData(formdata,callback){
chrome.runtime.sendMessage({data: formdata, method:
'storeform'},function(response) {
console.log(response.data);
});
}
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if(request.method == "storeform")
{
//do some work
});
}
我需要从监听器调用 sendData() 的回调函数。 在内容脚本和后台脚本之间有多个消息和进程。请帮忙。 这里后台脚本的返回是chrome.runtime.sendMessage的形式。
最佳答案
消息只是 JSON;它们不能包含函数。从内容脚本中,保存对回调函数的引用,然后在内容脚本和后台脚本之间传递消息时包含该 id。完成所有中间处理后,发送一条消息告诉内容脚本运行回调。当内容脚本收到带有回调 id 的消息时,查找回调函数并调用它。
内容脚本
var callbacks = {};
function sendData(formdata, callback) {
// good-enough unique id
var callbackId = (new Date()).getTime();
callbacks[callbackId] = callback;
chrome.runtime.sendMessage({
data: formdata,
method: 'storeform',
callbackId,
}, function(response) {
console.log(response.data);
});
}
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
// if message includes a callback id, call it
if (request.callbackId && callbacks[request.callbackId]) {
callbacks[request.callbackId]();
}
}
)
后台脚本
// everything done; call the callback
chrome.runtime.sendMessage({callbackId});
关于javascript - 如何处理后台脚本中内容脚本的回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44089184/