0

I tried to put some stuff in the local storage, but when I try to put the information of the local storage in a variable it says "undefined". So here is my code:

var data = {};
chrome.storage.local.get(["murl", "musername", "mpassword"], function(result){
    data["url"] = result.murl;
    data["username"] = result.musername;
    data["password"] = result.mpassword;
    alert(result.musername);
});
alert(data["username"]);

It first shows: undefined and then it shows Ebbez, also strange is when I remove the last line, I get Ebbez.

Rob W
  • 341,306
  • 83
  • 791
  • 678
Ebbez
  • 344
  • 1
  • 2
  • 13
  • 1
    This result is caused by asynchronicity of the `chrome.storage.local.get` method. As you've seen, putting the `alert(result.musername)` at the end of the callback results in the expected behavior. Why do you want to have `alert` after the `chrome.storage.local.get` method call? – Rob W Dec 22 '14 at 20:02
  • How's `alert` function show you anything? It's disabled in Chrome Apps. – Pawel Uchida-Psztyc Dec 22 '14 at 20:40
  • @jarrodek The question is tagged [tag:google-chrome-extension] – Xan Dec 22 '14 at 20:41
  • @Xan - oh, I see. It's not disabled in extension enviroment. – Pawel Uchida-Psztyc Dec 22 '14 at 20:47
  • I am using chrome.storage.sync right now, thanks all – Ebbez Dec 22 '14 at 21:11
  • 1
    possible duplicate of [Callback returns undefined with chrome.storage.sync.get](http://stackoverflow.com/questions/18699075/callback-returns-undefined-with-chrome-storage-sync-get) – Xan Dec 22 '14 at 22:15

1 Answers1

1

To store information you need the chrome.storage functions, here are some examples.

// Save 1 data item
chrome.storage.sync.set({"variableName":value});

// Save multiple data items
chrome.storage.sync.set({"variableName":value, "secondVariableName":secondValue});

// Load 1 data item
chrome.storage.sync.get("variableName", function(result){
    // Shows variable
    alert(result.variableName);
});

// Load multiple data items
chrome.storage.sync.get(["variableName", "secondVariableName"], function(results){
    // Shows multiple variables
    alert(results.variableName);
    alert(results.secondVariableName);
});
Ebbez
  • 344
  • 1
  • 2
  • 13