javascript - 异步使用onMessage.addListener的sendResponse

标签 javascript google-chrome-extension promise

我正在将 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/

相关文章:

javascript - AngularJS:forEach 和 http 获取数据 - 等待所有内容加载完毕

javascript - 阻止容器重叠

javascript - 用于在 fabricjs Canvas 上选择对象的事件处理程序

javascript - Chrome 扩展程序 : variable undefined in chrome extension even though it exists in console

javascript - 无法使用 Chrome 扩展程序设置 cookie

javascript - 返回 Promise 说 Promise Pending,Node js?

javascript - 在 d3 中,模糊事件仅在 Firefox 中不起作用

javascript - 将 CKEditor 集成到 elFinder

javascript - tabs.executeScript - 传递参数和使用库?

angular - 您将如何修复此 "Promise<any>' 提供与签名 '(value: any): {} | PromiseLike<{}>"不匹配的错误