Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chome extension: sending chrome.storage data from background script to popup/contentscript

As described in the title, I'm trying to write a background script that will listen for load requests from either the popup.js or contentscript.js. When it receives a load, it get the content of chrome.storage.local, performs a little bit of data processing(for loop) and sends it to the requester.

The current issue, is my code receives the request, but fails to send back the data. My code is listed below:

popup.js:

chrome.runtime.sendMessage({greeting: "Load"}, function(response) {
  console.log(response);
}

background.js:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if(request.greeting=='Load') {
    chrome.storage.local.get(null,function(storeObject){
      var newList=[];
      //Perform some dataprocessing to store part of storeObject into newList
      sendResponse(newList);
    });
  }
});

I think the issue is related to scope, since after debugging it looks like sendResponse is trying to send from chrome.storage instead of background.js. Also, if I send the message outside (before/after) the chrome.storage.local callback, popup.js receives the message.Regardless I'm pretty lost at what to do to get this message passing working and would appreciate any help.

like image 800
bkvchu Avatar asked Dec 01 '22 02:12

bkvchu


1 Answers

According to the docs on `chrome.runtime.onMessage:

sendResponse ( function )
[...]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).

Since, sendResponse is called asynchronously in chrome.storage.local.get()'s callback, you need to return true from the onMessage listener to prevent the function from being invalidated.

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.greeting === 'Load') {
        chrome.storage.local.get(null, function(storeObject) {
            ...
            sendResponse(newList);
        });
        return true;   // <-- I intend to call `sendResponse` later
    }
    return false;   // <-- I do NOT intend to call `sendResponse`
});
like image 62
gkalpak Avatar answered Dec 04 '22 09:12

gkalpak