我正在编写 chrome 扩展,但 sendResponse
方法不起作用。
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if(!request.method){
return false;
}
if(request.method=='postList' && request.post_list){
// alert(1);
a_facebook_api.getPostFromDB(request.post_list, function(data){
alert(data);
sendResponse(data);
});
} else if(request.method=='postAdd' && request.post_data){
a_facebook_api.addPostToDB(request.post_data, function(data){
sendResponse(data);
});
}
return true;
}
);
chrome.runtime.sendMessage({method: "postList",post_list: post_list}, function(response) {
alert(response);
});
函数 alert(data)
有效。它为我提供了 JSON 格式的正确数据。但是,alert(response)
不显示任何消息。谁能告诉我为什么它不起作用?
提前致谢!
最佳答案
您还没有说明这段代码是否在内容脚本或后台页面中。通过查看它,我认为它是内容脚本的一部分。
我在我自己的一个扩展程序中尝试了您的代码,它提示“[object Object]”,当您提示一个不是字符串或数值的变量时会发生这种情况。如果您将警报数据更改为“response.responseData”,它会从后台页面提醒您标记为“responseData”的值。
因为它没有为您发出任何警报,我认为正在监听消息的脚本没有正确响应。
我让代码正常工作。 这是内容脚本:
//Document ready
window.onload = function() {
alert('Ready');
//Send a message
sendMessage();
}
//Get message from background page
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
//Alert the message
alert("The message from the background page: " + request.greeting);//You have to choose which part of the response you want to display ie. request.greeting
//Construct & send a response
sendResponse({
response: "Message received"
});
});
//Send message to background page
function sendMessage() {
//Construct & send message
chrome.runtime.sendMessage({
method: "postList",
post_list: "ThePostList"
}, function(response) {
//Alert the message
alert("The response from the background page: " + response.response);//You have to choose which part of the response you want to display ie. response.response
});
}
这是后台脚本:
//Get message from content script
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
//Alert the message
alert('The message from the content script: ' + request.method);//You have to choose which part of the response you want to display ie. request.method
//Construct & send a response
sendResponse({
response: "Message received"
});
}
);
//Send message to content script
function sendDetails(sendData) {
//Select tab
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
//Construct & send message
chrome.tabs.sendMessage(tabs[0].id, {
greeting: sendData
}, function(response) {
//On response alert the response
alert("The response from the content script: " + response.response);//You have to choose which part of the response you want to display ie. response.response
});
});
}
每次脚本收到消息时,您都必须使用“sendResponse”函数发送响应。
希望这对您有所帮助。
关于javascript - chrome 扩展 `sendResponse` 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20435528/