我正在尝试在内容脚本和扩展程序之间传递消息
这是我在内容脚本中的内容
chrome.runtime.sendMessage({type: "getUrls"}, function(response) {
console.log(response)
});
在后台脚本中我有
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.type == "getUrls"){
getUrls(request, sender, sendResponse)
}
});
function getUrls(request, sender, sendResponse){
var resp = sendResponse;
$.ajax({
url: "http://localhost:3000/urls",
method: 'GET',
success: function(d){
resp({urls: d})
}
});
}
现在,如果我在 getUrls
函数中的 ajax 调用之前发送响应,则响应发送成功,但是在我发送响应时,在 ajax 调用的成功方法中它不发送它,当我进入调试时,我可以看到 sendResponse
函数的代码中的端口为空。
最佳答案
来自 the documentation for chrome.runtime.onMessage.addListener
:
This function becomes invalid when the event listener returns, unless you return true from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end until sendResponse is called).
所以你只需要在调用getUrls
之后加上return true;
,表示你将异步调用响应函数。
关于javascript - Chrome 扩展消息传递 : response not sent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20077487/