Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement "return true;"? Error: "The message port closed before a response was received."

How can I implement that my event-handler returns true? (Tried everything but the error returns)

I'm getting following error:

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

Solution is:

"Note: The sendResponse callback is only valid if used synchronously, or if the event handler returns true to indicate that it will respond asynchronously. The sendMessage function's callback will be invoked automatically if no handlers return true or if the sendResponse callback is garbage-collected."

https://developer.chrome.com/extensions/messaging#simple

edit: See also (chrome): https://github.com/mozilla/webextension-polyfill/issues/130

Here's my code, I would be very thankful:

// receive message from pop-up or options
chrome.extension.onMessage.addListener(function (aRequest, aSender, 
aSendResponse) {
    if (!aSender) {
        return;
    }
    switch (aRequest.cmd) {
        // reload lists
    case 'reload':
        XX.blockedDomains = {};
        XX.load();
        break;
        // send list of recently blocked
    case 'blocked':
        aSendResponse(Object.keys(XX.blockedDomains));
        break;
        // deny domain
    case 'deny':
        XX.blocklist[aRequest.domain] = 1;
        delete XX.blockedDomains[aRequest.domain];
        XX.save();
        break;
    }
});
like image 395
Aldunnord Avatar asked Dec 17 '22 18:12

Aldunnord


1 Answers

Seems fixed now. I added return true; on the second last line and now there are no more error entries in the log.

Is this solution ok? Would be glad for feedback if something is wrong with it. Otherwise, I will mark this thread in a few days as solved.

// receive message from pop-up or options
chrome.extension.onMessage.addListener(function (aRequest, aSender, 
aSendResponse) {
    if (!aSender) {
        return;
    }
    switch (aRequest.cmd) {
        // reload lists
    case 'reload':
        XX.blockedDomains = {};
        XX.load();
        break;
        // send list of recently blocked
    case 'blocked':
        aSendResponse(Object.keys(XX.blockedDomains));
        break;
        // deny domain
    case 'deny':
        XX.blocklist[aRequest.domain] = 1;
        delete XX.blockedDomains[aRequest.domain];
        XX.save();
        break;
    }
    return true;
});
like image 105
Aldunnord Avatar answered Feb 10 '23 05:02

Aldunnord