2017-08-27 78 views
0

我在看这个网页上的代码演示:https://developer.chrome.com/apps/messaging为什么我需要在一次性请求中使用“sendResponse”?

的代码是这样的:

Content.js

chrome.runtime.sendMessage({greeting: "hello"}, function(response) { 
    console.log(response.farewell); 
}); 

Background.js

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) { 
    console.log(sender.tab ? 
      "from a content script:" + sender.tab.url : 
      "from the extension"); 
    if (request.greeting == "hello") 
    sendResponse({farewell: "goodbye"}); 
}); 

我主要理解t他编码,但有一点我不明白是“sendResponse”。如果我删除sendResponse({farewell: "goodbye"});,代码仍然正常工作,这是很好的。但是,如果我从function(request, sender, sendResponse) {中删除sendResponse,则扩展名不会随消息传递一起执行。所以基本上我想知道为什么我需要这个参数,即使我不使用它。谢谢

回答

2

如果您不打算使用它,则不需要sendResponse()

确保您排除sendResponse回调参数:

// no sendResponse arg 
function(request, sender) { 

,并删除您的来电:

// remove this 
sendResponse({farewell: "goodbye"}); 

最后,不要试图从响应登录告别,因为它赢得了” t存在:

// remove this 
console.log(response.farewell); 
相关问题