1

I'm learning Chrome Extensions. Here is a script from background.js that will receive the response message from content.js.

function saveCdKey() {
  var cdKeyJson = new Array();
  storageType.set(cdKeySettings, function() {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      chrome.tabs.sendMessage(tabs[0].id, {message: "getCdKeys"}, function(response) {
        //console.log(response.message);
        cdKeyJson = response.message;
      });
    });

    console.log(cdKeyJson);
  });
}

Assuming that I always get the message back from the content.js which is an array. I want to save the response.message into the cdKeyJson for later use in the script. However, when I assign it inside the send message function, it will be empty when I call it later. I.e: when I do console.log on cdKeyJson, it's an empty array. I'm still learning JS so is it anyway that I can save the response for later use? Thank you.

Kiddo
  • 1,910
  • 8
  • 30
  • 54
  • 2
    Both chrome.tabs.query and chrome.tabs.sendMessage are asynchronous, so you console.log will execute before cdKeyJson has a value. – James Oct 31 '17 at 16:05
  • Possible duplicate of [How to return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – StudioTime Oct 31 '17 at 16:16
  • 1
    Look at [localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) and [sessionStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage). If you're not overly concerned about security then they will give you what you need. – Reinstate Monica Cellio Oct 31 '17 at 16:19
  • This isn't a duplicate of that question - yes, they need to understand why the value isn't stored in the way they expect, but they also need the rest of the question answering. – Reinstate Monica Cellio Oct 31 '17 at 16:20
  • Thanks all. localStorage helps in my case since I just pass the web content around the js files which is not private, but the answer from Darren and James also helped to understand the problem I have. – Kiddo Oct 31 '17 at 16:24

0 Answers0