Javascript onMessage.addListener:sendResponse

Javascript onMessage.addListener:sendResponse,javascript,google-chrome-extension,Javascript,Google Chrome Extension,如果已经给出了答案,请原谅,我已经搜索了1个多小时,但没有找到解决问题的方法 这就是我的问题: 我正在编写一个chrome扩展,有两个JS脚本,“script.JS”和“background.JS”。在我的script.js中,我使用chrome.runtime.sendMessage向我的后台脚本发送消息 使用我的背景脚本,我让一个监听器接收消息并从消息提供的链接下载几个图像,这意味着在下载完成之前,该功能可能需要1分钟。(顺便说一句,我正在使用promise,这样我就知道我的代码是一步一步执

如果已经给出了答案,请原谅,我已经搜索了1个多小时,但没有找到解决问题的方法

这就是我的问题:

我正在编写一个chrome扩展,有两个JS脚本,“script.JS”和“background.JS”。在我的script.js中,我使用
chrome.runtime.sendMessage
向我的后台脚本发送消息

使用我的背景脚本,我让一个监听器接收消息并从消息提供的链接下载几个图像,这意味着在下载完成之前,该功能可能需要1分钟。(顺便说一句,我正在使用promise,这样我就知道我的代码是一步一步执行的)

script.js

chrome.runtime.sendMessage({message: "download", parameters: images}, function (response) {
    console.log(response);
});
chrome.runtime.sendMessage({message: "download", "parameters": images});
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    console.log(request);
});
background.js

chrome.runtime.onMessage.addListener(function (arg, sender, sendResponse) {
    doSomeLongStuff().then(function () {
        sendResponse(myResponse);
        return true;
    })
});
chrome.runtime.onMessage.addListener(function (arg, sender, sendResponse) {
    doSomeLongStuff().then(function () {
        chrome.tabs.sendMessage(sender.tab.id, {'status': 'finished'});
    })
});
在我的剧本中,我无法得到我的答案。即使我向responseCallback添加一个setInterval,响应也将始终是
未定义的


如果有人能告诉我是否有办法让响应Callback等待长时间的回答,我们将不胜感激。

这是一个常见问题,即从异步操作返回响应。如果没有同步执行,Chrome将忽略对
sendResponse()
的任何调用

解决方案不是从发送响应的角度来考虑,而是以自己的方式发送后续消息

chrome.runtime.onMessage.addListener(function (arg, sender, sendResponse) {
    doSomeLongStuff().then(function () {
        //don't call sendResponse() here, send a separate message to script.js
        return true;
    })
});
您可以通过回调中的
chrome.tabs.sendMessage
发送此消息,以请求
chrome.tabs.query

解决方案:

Utkanos给出了正确的答案,因此,如果有人在寻找相同的答案,那么下面就是它现在的工作方式:

script.js

chrome.runtime.sendMessage({message: "download", parameters: images}, function (response) {
    console.log(response);
});
chrome.runtime.sendMessage({message: "download", "parameters": images});
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    console.log(request);
});
background.js

chrome.runtime.onMessage.addListener(function (arg, sender, sendResponse) {
    doSomeLongStuff().then(function () {
        sendResponse(myResponse);
        return true;
    })
});
chrome.runtime.onMessage.addListener(function (arg, sender, sendResponse) {
    doSomeLongStuff().then(function () {
        chrome.tabs.sendMessage(sender.tab.id, {'status': 'finished'});
    })
});

谢谢,这正是我想要的帮助:我们可以从侦听器的
发送者
参数访问
选项卡.id
。问题中的代码(以及此答案)是错误的:
返回true
应该在异步子函数调用之外,因为其思想是从侦听器返回true,以告知调用侦听器的API等待。当放置在正确的位置时,它在异步调用中启用sendResponse,无需发送另一条消息。@wOxxOm完全没有注意到返回-显然是错误的。其他答案的可能重复项显示在错误的位置
return true
,因此您可以简化代码:无需发送另一条消息。确保始终检查文档。