1

Edit: I gave up and decided to store the data in the storage.local of the popup.

I am sending a message from the popup to the background to fetch some data from storage.local (when I do it from the popup it just returns an empty map). The background should respond with a map.

The problem is that before the response from the background is sent, the response is a map with values, but after the response, it's "undefined".

popup.js

    window.addEventListener('DOMContentLoaded', () => {
        chrome.runtime.sendMessage({subject:"config"},function(response){
          // prints undefined
          console.log(response);
        });
    });

background.js

    chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
      if(request.subject == "config"){
        (async () => {
          chrome.storage.local.get("config2t2b", function(result){
            
            //prints a map
            console.log(result.config2t2b);
            sendResponse(result.config2t2b);
            return;
          });
        })();
      }
    }
    );

3
  • It's a Firefox add-on though you are using chrome object? In theory the code you have should work. Commented Apr 7 at 13:34
  • Sorry, I didn't add the chrome extension tag. I use chrome because otherwise, it wouldn't work in chromium based browsers. Commented Apr 7 at 13:47
  • globalThis.browser ??= globalThis.chrome;. Did you really give on the the original question? Commented Apr 7 at 13:52

1 Answer 1

1

I think the issue you're facing is due to how sendResponse works when used inside an asynchronous callback like chrome.storage.local.get. The listener must explicitly return true to indicate that the response will be sent asynchronously. Update your background.js to return true from the listener. Chrome needs to know that the sendResponse call will be made asynchronously. If true is not returned, Chrome assumes the listener is done and discards the response once the function exits. Returning true keeps the message channel open.

chrome.runtime.onMessage.addListener(
      function(request, sender, sendResponse) {
        if (request.subject === "config") {
          chrome.storage.local.get("config2t2b", function(result) {
            console.log(result.config2t2b); // prints a map
            sendResponse(result.config2t2b);
          });
          // Tells Chrome we will respond asynchronously
          return true;
        }
      }
    );

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.