Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid "The message port closed before a response was received" error when using await in the listener

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?

like image 702
Kyle Hu Avatar asked Jan 03 '19 06:01

Kyle Hu


1 Answers

const asyncFunctionWithAwait = async (request, sender, sendResponse) => {...}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    asyncFunctionWithAwait(request, sender, sendResponse)

    return true
})

worked for me

like image 103
RomanistHere Avatar answered Oct 17 '22 13:10

RomanistHere