1

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! :)

theMaxx
  • 3,756
  • 2
  • 27
  • 33
  • See this answer to learn what's wrong with your code, and how to solve it: http://stackoverflow.com/a/11689804/938089 – Rob W Aug 31 '12 at 12:23

1 Answers1

3

Because the response is in the callback function. When you have this:

chrome.extension.sendMessage({greeting:"color"},function(response){color = response.farewell;});

alert('content - ' + color);

The browser executes sendMessage and then IMMEDIATELY goes ot the next line, the alert. The callback in sendMessage is fired after. The alert 'fixes' it because you are basically pausing the browser. If you want to use color as a variable, you can only use it inside the callback: function(response).

Rob W
  • 341,306
  • 83
  • 791
  • 678
Raymond Camden
  • 10,661
  • 3
  • 34
  • 68