gpt4 book ai didi

javascript - Chrome 扩展程序未收到响应

转载 作者:行者123 更新时间:2023-12-02 14:35:54 25 4
gpt4 key购买 nike

我试图获取从sendResponse到chrome.runtime.sendMessage的响应,但它总是显示未定义,下面是我的代码:

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({success: true}) 时,应该在 chrome.runtime.sendMessage 的回调中收到它,但它显示未定义。

最佳答案

该问题可能是由于 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:

Function to call (at most once) when you have a response. The argument should be any JSON-ifiable object. If you have more than one onMessage listener in the same document, then only one may send a response. 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).

关于javascript - Chrome 扩展程序未收到响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37457702/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com