0

I am creating a chrome extension and to my surprise my content script is acting very odd. I have defined a global variable keyword but when it goes through the function that gives it it's value, the value expires when the function ends. I've spent hours troubleshooting and can't seem to find the problem.

var keyword;

chrome.extension.sendMessage({localStorage: "yo"}, function(response) {
        var localStorage = response.localStorage;
        keyword = localStorage["keyword"];
        console.log(keyword);
});
console.log(keyword);

The log within the function returns my desired value, but the log after the function returns undefined, even though as far as I can tell, it should also return the value that was given to it within the function. I did not declare it within the function, so why does it's value expire after the function?

1 Answers1

0

The value to "keyword" is assigned in some kind of callback function as it seems in your example. So if you run your code, the callback function will not be executed immediately, so no value is assigned to "keyword". It will be executed later, when your chrome extensions fires the callback function, you passed to "sendMessage".

But your console.log will be executed immediately and "keyword" is like it was initialized - undefined.

Lord Midi
  • 754
  • 1
  • 9
  • 25