I am writing a chrome extension with node module "chrome-extension-async" and meeting a problem when use await
in the listener of background.
The content.js which will be injected into the page will send a message to the background, asking it to do some IO operations which is async:
// content.js
const package = await chrome.runtime.sendMessage({param: ...})
console.log(package)
// background.js
chrome.runtime.onMessage.addListener(async (request, sender,
sendResponse) => {
const value = await doIOOperation();
sendResponse(value);
})
However, chrome will report errors like below:
Uncaught (in promise) Error: The message port closed before a response was received.
I think there must be some conflict when using async/await in the listener, Anyone know how to solve this problem?
return true
just like with the classic callback version, but the listener can't beasync
- you'll have to put the async code into IIFE or another function. I also think the WebExtension polyfill is better and BTW it correctly handles this case. – wOxxOm Jan 3 '19 at 7:04sendResponse
is planned to be phased out from the W3C draft. And it is to be replaced by returning a Promise. I'm assuming this is now happening on Chrome, with some users reporting that this issue is happening on Chrome 71. developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/… – tom_mai78101 Jan 11 '19 at 14:20