I have a basic Google Chrome Extension I am working on, and having a problem getting a value from localStorage. I am using sendMessage in the content script to ask for the variable from the background page. When I get the response, the variable is always "undefined", unless I put something like an alert() after the response...then the variable contains my value. Can you help me to figure out why this is and how to do it correctly? I have made the code for this post and it is below. Thank you very much!
manifest.json
{
"name": "Test Extension",
"version": "1.0",
"manifest_version": 2,
"description": "A test extension.",
"background": {
"scripts": ["background.js"]
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
],
"permissions": [
"tabs", "<all_urls>"
]
}
content.js
alert('content');
var color;
chrome.extension.sendMessage({greeting:"color"},function(response){color = response.farewell;});
// alert('pause'); // uncommenting this line lets me get the value...why?
alert('content - ' + color);
background.js
alert('background');
localStorage["color"] = "lightblue";
var color = localStorage["color"];
alert('background - ' + color);
chrome.extension.onMessage.addListener(function(request,sender,sendResponse)
{
if (request.greeting == "color") {sendResponse({farewell:color});}
});
Thank you very much for any help! :)