14
votes

I'm developing an extension for Google Chrome, and have run into some trouble.I created an options.html page and added it to the manifest.json file.The page shows properly.

I saved the options, and then went back to the page on which the extension is supposed to run.

Unfortunately, the Local storage for the options was returning a 'null' instead of the option. If I set the local storage option directly from the extension's JS script, it works fine but not if it was set from the options page.

Any idea how i can access the options.html local storage values from my Javascript file in the extension?

2
So how did you fix it? I'm having the same problem. options.html uses localStorage, but the content script knows only the website's localStorage and background.js's localStorage is empty... - Rudie
I've fixed it using the new storage API: developer.chrome.com/extensions/storage.html - Rudie
At this point, you should be using chrome.storage, not localStorage in Chrome extensions, unless it is specifically your intent to interact with the localStorage for a specific website using a content script. - Makyen

2 Answers

25
votes

You can set them using either

localStorage["var"]=data;

or

localStorage.var=data;

Load them using

var myvar = localStorage.var;

You can read about the API here.

13
votes

The correct method is:

if (typeof(localStorage) == ‘undefined’ ) {
  alert(‘Your browser does not support HTML5 localStorage. Try upgrading.’);
}
else {
  try {
    localStorage.setItem(“name”, “Hello World!”); //saves to the database, “key”, “value”
  }
  catch (e) {
    if (e == QUOTA_EXCEEDED_ERR) {
      alert(‘Quota exceeded!’); //data wasn’t successfully saved due to quota exceed so throw an error
    }
  }
  document.write(localStorage.getItem(“name”)); //Hello World!
  localStorage.removeItem(“name”); //deletes the matching item from the database
}

REFERENCE: http://html5tutorial.net/tutorials/working-with-html5-localstorage.html