Monday, April 19, 2021

Unchecked runtime.lastError: The message port closed before a response was received.

Even if the listener's async code returns true to indicate it is running an async code, the code will still have the error "Unchecked runtime.lastError: The message port closed before a response was received" if the async code is wrongly placed.
The following code produces the error mentioned due to misplaced async
chrome.runtime.onMessage.addListener(async (message /* , sender, sendResponse */) => {
    if (message.action === UPDATE_PAGE) {
        await applyStyleFromSettings();
    }
    // https://stackoverflow.com/questions/53024819/chrome-extension-sendresponse-not-waiting-for-async-function    
    return true;
});
Returning true is not enough, to fully fix the problem, we must place the async code on the code body itself, not on the callback's declaration. Remove the async declaration from the listener, move it to the code's body instead
chrome.runtime.onMessage.addListener((message /*, sender, sendResponse */) => {
    (async () => {
        if (message.action === UPDATE_PAGE) {
            await applyStyleFromSettings();
        }
    })();
    // https://stackoverflow.com/questions/53024819/chrome-extension-sendresponse-not-waiting-for-async-function            
    return true;
});

No comments:

Post a Comment