views:

1542

answers:

4

Is it possible to store data in a way that will be accessible after a browser restart in the context of a chrome extension?

+9  A: 

Yes, it is. Going over a full walkthrough of how to do this would probably exceed the length of a reasonable StackOverflow answer, so I'll refer you to this very extensive tutorial by Rajdeep Dua.

The relevant code would look like this:

  // Store item in local storage:
  function setItem(key, value) {
    try {
      log("Storing [" + key + ":" + value + "]");
      window.localStorage.removeItem(key);      // <-- Local storage!
      window.localStorage.setItem(key, value);  // <-- Local storage!
    } catch(e) {
      log("Error inside setItem");
      log(e);
    }
    log("Return from setItem" + key + ":" +  value);
  }

  // Gets item from local storage with specified key.
  function getItem(key) {
    var value;
    log('Retrieving key [' + key + ']');
    try {
      value = window.localStorage.getItem(key);  // <-- Local storage!
    }catch(e) {
      log("Error inside getItem() for key:" + key);
      log(e);
      value = "null";
    }
    log("Returning value: " + value);
    return value;
  }

  // Clears all key/value pairs in local storage.
  function clearStrg() {
    log('about to clear local storage');
    window.localStorage.clear(); // <-- Local storage!
    log('cleared');
  }

  function log(txt) {
    if(logging) {
      console.log(txt);
    }
  }
John Feminella
+2  A: 

The new chrome version has local storage.

http://www.rajdeepd.com/articles/chrome/localstrg/LocalStorageSample.htm

Patrick Cornelissen
+2  A: 

even simpler than that:

to read:

var myStoredValue = localStorage["TheKeyToMyStoredValue"];

to write:

localStorage["TheKeyToMyStoredValue"] = myNewValueToStore;

to get rid of:

delete localStorage["TheKeyToMyStoredValue"];
Martin Bartlett
+2  A: 

Chrome also supports the HTML5 Web Database spec. This gives you a local SQL database, so you can do more complex things than simply storing name/value pairs in Local Storage.

Ken Liu

related questions