2016-05-26 88 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

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