Do Chrome extensions have access to local storage?

2019-01-31 02:19发布

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

6条回答
祖国的老花朵
2楼-- · 2019-01-31 02:51

even simpler than that:

to read:

var myStoredValue = localStorage["TheKeyToMyStoredValue"];

to write:

localStorage["TheKeyToMyStoredValue"] = myNewValueToStore;

to get rid of:

delete localStorage["TheKeyToMyStoredValue"];
查看更多
叼着烟拽天下
3楼-- · 2019-01-31 02:53

Nowadays it might be better to use chrome.storage chrome.storage is asynchronous, which makes it faster and localStorage is limited to 5MB.

查看更多
何必那么认真
4楼-- · 2019-01-31 02:56

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);
    }
  }
查看更多
倾城 Initia
5楼-- · 2019-01-31 03:07

The current chrome version has local storage.

I have used it myself. You can use modernizr to detect whether the browser supports it or not. I have written a solution for a client where I do a fallback to cookie if no local storage exists, but this shouldn't be a problem for extensions.

查看更多
\"骚年 ilove
6楼-- · 2019-01-31 03:10

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.

查看更多
Evening l夕情丶
7楼-- · 2019-01-31 03:14

there are already some great answers here, but note that if you decide to use a content script in your extension, that content script won't have access to localStorage. therefore chrome.storage is a good alternative.

查看更多
登录 后发表回答