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?
const asyncFunctionWithAwait = async (request, sender, sendResponse) => {...}
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
asyncFunctionWithAwait(request, sender, sendResponse)
return true
})
worked for me
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With