我正在将 Chrome 扩展程序与后台脚本连接起来。 对于简单的同步调用,它工作得很好。我发送一条消息并得到回复。
显然,下面的getValue
,它在内部使用 IndexedDB 和 Dexie Promise,不允许使用简单的 sendResponse
。我看到处理这个问题的方法是发送消息作为响应。
然而,对于我来说,这并没有什么意义。后台脚本只是检查是否要在数据库中找到特定键的值。扩展应该一直阻塞,直到返回键的值。
我可以以某种方式展开它以使用 sendResponse
?也许包裹return findData()
进入同步函数?
chrome.runtime.sendMessage({
request:'getValue',
key: shortcutKey
}, (data) => {
debugLog('getShortcut:', data);
let value = data.value;
console.log(`for key: ${key} found ${value}`);
...
do_my_thing();
});
后台脚本:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
switch (request.name) {
case 'getClipboard':
sendResponse({clipboard:getClipboard()});
break;
case 'getValue':
console.log(`background::getValue handler key:`, request.key);
return findData(request.key.substring(constants.PREFIX.length)).then((result) => {
console.log(`findData return: ${result}`);
sendResponse( { value: result });
});
break;
...
}
});
最佳答案
在异步情况下只需返回 true
!
Note: The sendResponse callback is only valid if used synchronously, or if the event handler returns true to indicate that it will respond asynchronously. The sendMessage function's callback will be invoked automatically if no handlers return true or if the sendResponse callback is garbage-collected. https://developer.chrome.com/apps/messaging
关于javascript - 异步使用onMessage.addListener的sendResponse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46257843/