gpt4 book ai didi

javascript - Chrome扩展消息传递: response not sent

转载 作者:行者123 更新时间:2023-11-28 08:33:40 27 4
gpt4 key购买 nike

我正在尝试在内容脚本和扩展程序之间传递消息

这是我在内容脚本中的内容

chrome.runtime.sendMessage({type: "getUrls"}, function(response) {
console.log(response)
});

在后台脚本中我有

chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.type == "getUrls"){
getUrls(request, sender, sendResponse)
}
});

function getUrls(request, sender, sendResponse){
var resp = sendResponse;
$.ajax({
url: "http://localhost:3000/urls",
method: 'GET',
success: function(d){
resp({urls: d})
}
});

}

现在,如果我在 getUrls 函数中的 ajax 调用之前发送响应,则响应已成功发送,但在 ajax 调用的 success 方法中,当我发送响应时,它不会发送它,当我进入调试时,我可以看到 sendResponse 函数的代码中的端口为空。

最佳答案

来自the documentation for chrome.runtime.onMessage.addListener :

If you want to asynchronously use sendResponse(), add return true; to the onMessage event handler.

因此,您只需在调用 getUrls 后添加 return true; 即可表明您将异步调用响应函数。

请注意,其他文档(例如 the onMessage documentation )中没有提到这一点,因此开发人员可能会错过这一点。

关于javascript - Chrome扩展消息传递: response not sent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21516118/

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