2017-08-27 40 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); 
相關問題