Home > Web Front-end > JS Tutorial > body text

Why Doesn\'t `sendResponse` Wait for My Async Function in a Chrome Extension\'s `onMessage` Listener?

Patricia Arquette
Release: 2024-11-26 04:02:08
Original
452 people have browsed it

Why Doesn't `sendResponse` Wait for My Async Function in a Chrome Extension's `onMessage` Listener?

sendResponse Not Waiting for Async Function or Promise's Resolve

Problem:
Asynchronicity issue where sendResponse() in contentscript.js does not pause until getThumbnails() returns. Additionally, payload in getThumbnails() is frequently null, indicating a potential incomplete execution.

Analysis:
Chrome does not support Promises in the returned value of onMessage listeners in both ManifestV3 and V2. This means that the sendResponse Promise returned by the async listener is ignored, and the port is closed immediately.

Solution:
To make the listener compatible:

  1. Remove the async keyword from the onMessage event listener.
  2. Create a separate async function and call it from the event listener. For example:
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  if (msg.message === "get_thumbnails") {
    processMessage(msg).then(sendResponse);
    return true; // keep the messaging channel open for sendResponse
  }
});

async function processMessage(msg) {
  console.log('Processing message', msg);
  // .................
  return 'foo';
}
Copy after login

To patch the API to allow an async/Promise listener:

  1. Add the following code to the top of each script that uses chrome.runtime.onMessage:
if ('crbug.com/1185241') { // replace with a check for Chrome version that fixes the bug
  const {onMessage} = chrome.runtime, {addListener} = onMessage; 
  onMessage.addListener = fn => addListener.call(onMessage, (msg, sender, respond) => {
    const res = fn(msg, sender, respond);
    if (res instanceof Promise) return !!res.then(respond, console.error);
    if (res !== undefined) respond(res);
  });
}
Copy after login
  1. You can then simply return the value from the async listener:
chrome.runtime.onMessage.addListener(async msg => {
  if (msg === 'foo') {
    const res = await fetch('https://foo/bar');
    const payload = await res.text();
    return {payload};
  }
});
Copy after login

The above is the detailed content of Why Doesn\'t `sendResponse` Wait for My Async Function in a Chrome Extension\'s `onMessage` Listener?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template