Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What caused the "Unchecked runtime.lastError: The message port closed before a response was received." warning?

I have searched around but it's all about people complaining the bug. Many posts say that you should check all your extensions.

However, this is something I encountered when I am developing an extension.

Here is how it happens:

I have a listener on background.js:

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
  console.log('get:', request);
  if (request.hasOwnProperty('opt')) {
    trackPage('opt/' + request.opt);
  }
  return Promise.resolve("");
});

And here is the trigger in my option page:

track('something');
function track(msg){
  chrome.runtime.sendMessage({opt: msg}, function(response) {
    console.log(response);
  });
}

The error occurs when the track function is fired.

How can I fix the error totally?

like image 586
darkrose1977 Avatar asked Mar 18 '19 15:03

darkrose1977


1 Answers

You can't return a Promise to make the function async, you have to return true. So change this:

return Promise.resolve("");

To this:

Promise.resolve("").then(result => sendResponse(result));
return true;
like image 117
GirkovArpa Avatar answered Sep 29 '22 13:09

GirkovArpa