-1

I am setting chrome.local variables in pop.js but unable to retrieve them in content.js

popup.js

chrome.storage.local.set('TITLE',title);

content.js

var title = null;
    $(".class").each(function () {
          chrome.storage.local.get('TITLE', function (result) {
                                    title = result.TITLE;
                    console.log('inside'+title);//prints value
                                });


    }

  console.log(title);//returns null;

It returns title as null

Chrome Console outputs as:

outside: null
content.js:42 insideJava: A Beginner's Guide, Sixth Edition
Volatil3
  • 14,253
  • 38
  • 134
  • 263
  • Are you sure that the `title` variable has a value in **popup.js**? Perhaps you could also try `console.log`ing `result`, in **content.js**? – Brynden May 14 '16 at 03:08
  • @BryndenBielefeld I checked it's not even entering in `get` code block. Further explaination added – Volatil3 May 14 '16 at 03:09
  • It sounds like the problem is coming from elsewhere in your code. I see you've updated your question. If `title` is declared in **content.js**, I do believe it is out of scope. Where have you defined it? – Brynden May 14 '16 at 03:11
  • I just re-read your comment, you said "it's not even entering the `get` block". Perhaps there aren't any elements on the page that can be selected with the CSS-selector that you provided to jQuery. – Brynden May 14 '16 at 03:15
  • @BryndenBielefeld I am checking further, code is broken before that I guess – Volatil3 May 14 '16 at 03:16
  • @BryndenBielefeld What actually is happening, the value of `title` is accessed before the `get` block, may be because it's asynchronous. Question updated further. Question updated – Volatil3 May 14 '16 at 03:21
  • `chrome.storage.local.get` is asynchronous, yes, so you'll need to restructure your code to account for that. If possible, it might be best to do whatever you need to do with `title`, inside the `get` block, rather than trying to do it *after*. – Brynden May 14 '16 at 03:27

1 Answers1

0

chrome.storage.local.get is an asynchronous call, which means when you call console.log(title);, callback of chrome.storage.local.get has not been executed, then title remains null. You should put your logic inside the callback.

Haibara Ai
  • 10,703
  • 2
  • 31
  • 47