Home  >  Article  >  Web Front-end  >  How Can I Make `sendResponse` Wait for Async Functions in Chrome Extensions?

How Can I Make `sendResponse` Wait for Async Functions in Chrome Extensions?

DDD
DDDOriginal
2024-11-23 20:21:09162browse

How Can I Make `sendResponse` Wait for Async Functions in Chrome Extensions?

sendResponse Waits for Async Functions and Promise Resolves

Problem: In a Chrome extension, sendResponse() in contentscript.js does not pause for getThumbnails() to finish.

Explanation: Chrome's chrome.runtime.onMessage event listener returns a boolean value to indicate whether the channel should be kept open for sendResponse. When an async function or Promise is returned, Chrome ignores the Promise and closes the channel immediately.

Solution: Make the event listener compatible with async functions:

  1. Remove the async keyword: Remove the async keyword from the start of the event listener function.
  2. Define a separate async function: Create a separate async function that handles the message processing. Call this function from within the event listener.

Example:

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  if (msg.message === "get_thumbnails") {
    processMessage(msg).then(sendResponse);
    return true; // Keep the channel open for sendResponse
  }
});

async function processMessage(msg) {
  console.log('Processing message', msg);
  // ... Handle the message processing here ...
  return 'foo';
}

Alternative Solution: Patch the API

Add the following code to the beginning of every 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);
  });
}

This patch allows the event listener to return an async function or Promise.

The above is the detailed content of How Can I Make `sendResponse` Wait for Async Functions in Chrome Extensions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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
Previous article:Var Vs Let Vs ConstNext article:Var Vs Let Vs Const