2016-05-26 87 views
0

我想從sendResponse到chrome.runtime.sendMessage的反應,但它總是呈現不確定的,下面是我的代碼:沒有得到響應的Chrome extention

chrome.runtime.sendMessage(JSON.stringify(contact), function(response) { 
    console.log('Response: ', response); // This is showing undefined 
}); 

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { 
    contact.addContact(request, function() { 
     sendResponse({success: 'true'}); 
    }); 
}); 

所以,當我通過sendResponse({成功:true})應該在chrome.runtime.sendMessage的回調函數中接收,但不是它顯示爲undefined。

回答

2

該問題可能是由異步的contact.addContact造成的。這意味着偵聽器在調用sendResponse之前結束。從聽者返回true這應該修復它:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { 
    contact.addContact(request, function() { 
     sendResponse({success: 'true'}); 
    }); 
    return true; 
}); 

documentation of chrome.runtime.onMessage

sendResponse

函數調用(最多一次),當你有一個響應。參數 應該是任何JSON對象。如果在同一文檔中有多個onMessage偵聽器,則只有一個 可能發送響應。當事件 監聽的回報,除非你從事件​​偵聽器到 指示要異步發送一個響應返回true(這將讓 消息通道開放的另一端,直到sendResponse是 此功能無效所謂的)。

+0

是的工作,非常感謝... :) –