0

I am trying to communicate between the popup.js file and the background.js file for a chrome extension. However when retrieving information using the chrome storage, the execution of the callback no longer is received by the client (popup.js)

within the background.js file.

function getTotals(callback){
  chrome.storage.sync.get(LMSCats, function(data){
    callback({"results": data}); // does not work
  });
}

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    // sendResponse({"message": "hi"}); //works
    getTotals(sendResponse);
  }
}

Within the popup.js referenced from the popup.html file

chrome.runtime.sendMessage({action: "total"}, function(data){
    console.log(data);
});

I am not sure if I'm missing something from the documentation so any help will be appreciated. I came across chrome extension onMessage however I wasn't sure if this is related or how to get around this.

kyleED
  • 2,327
  • 2
  • 18
  • 23

1 Answers1

1

I didn't read properly

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    // sendResponse({"message": "hi"}); //works
    getTotals(sendResponse);
    return true;
  }
}

Solved the problem:

According to the documentation

This function becomes invalid when the event listener returns, unless you return true from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end until sendResponse is called).

Hope this helps someone else in the future.

kyleED
  • 2,327
  • 2
  • 18
  • 23