带有异步等待的 chrome.runtime.onMessage 响应

2024-04-20

我想在 onMessage 侦听器中使用异步等待:

chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) =>{
    var key = await getKey();
    sendResponse(key);
});

但是,当我发送消息时,我得到了未定义的信息。

来自chrome.runtime.onMessage.addListener 的文档 https://developer.chrome.com/docs/extensions/mv3/messaging/#simple:

如果想异步使用sendResponse(),添加return true;到 onMessage 事件处理程序。

当我使用回调时这有效。

chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) =>{
    getKey(key => {
        sendResponse(key);
    });
    return true;
});

不过我想利用await 语法。但它似乎不起作用并且仍然返回未定义:

chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) =>{
    var key = await getKey();
    sendResponse(key);
    return true;
});

tl;dr

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  (async () => {
    // async code goes here
    // ...
    const result = await getSomething();
    sendResponse(result);
  })();

  // Important! Return true to indicate you want to send a response asynchronously
  return true;
});

或者提取到异步函数。

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  doSomethingWith(request).then(sendResponse);
  return true; // return true to indicate you want to send a response asynchronously
});

async function doSomethingWith(request) {
  var key = await getKey();
  // await .....
  return key;
}

返回值async函数被隐式包装在Promise.resolve. See 异步文档 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function.

The return true;声明成功了。它告诉 Chrome 您想要异步发送响应。

See 消息上 https://developer.chrome.com/apps/runtime#event-onMessage.

或提取到实用程序

如果您认为您会最频繁地使用它,请创建一个实用程序,例如:

const wrapAsyncFunction = (listener) => (request, sender, sendResponse) => {
  // the listener(...) might return a non-promise result (not an async function), so we wrap it with Promise.resolve()
  Promise.resolve(listener(request, sender)).then(sendResponse);
  return true; // return true to indicate you want to send a response asynchronously
};

chrome.runtime.onMessage.addListener(
  wrapAsyncFunction(async (request, sender) => {
    console.log(request, sender);

    const key = await getKey();
    // await .....
    return key;
  })
);

或者更通用的

Use mozilla/webextension-polyfill https://github.com/mozilla/webextension-polyfill#basic-setup-with-module-bundlers如果您更喜欢“跨浏览器”扩展。

Example:

var browser = require("webextension-polyfill");

browser.runtime.onMessage.addListener(async (msg, sender) => {
  console.log("BG page received message", msg, "from", sender);
  console.log("Stored data", await browser.storage.local.get());
});

browser.browserAction.onClicked.addListener(() => {
  browser.tabs.executeScript({file: "content.js"});
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

带有异步等待的 chrome.runtime.onMessage 响应 的相关文章