HTML API

The localstorage API has two types: localStorage and sessionStorage, which exist in the window object: LocalStorage corresponds to window.localStorage and sessionStorage corresponds to window.sessionStorage. LocalStorage differs from sessionStorage mainly in its lifetime.

Basic usage

localStorage.setItem("b"."isaac");// Set b to "Isaac"
var b = localStorage.getItem("b");// Get the value of b, which is "Isaac"
var a = localStorage.key(0); // Get the key name of the 0th data item, in this case "b"
localStorage.removeItem("b");// Clear the c value
localStorage.clear();// Clear all localstorage data under the current domain name
Copy the code

scope

  • Here,scopeHow to separate the localStorage between different pages (total can not read Tencent localStorage on baidu’s page, ha ha ha).
  • localStorageAs long as the same protocol, the same host name, the same port, can read/modify to the same localStorage data.
  • sessionStoragethanlocalStorageMore stringent, in addition to protocol, host name, port, but also require the samewindow(that is, the browser TAB).

The lifetime

In theory, localStorage is permanently valid, that is, it will not disappear if you do not actively delete the data. Even if the size of the saved data exceeds the specified size of the browser, it will not delete the old data but will only report an error. However, it should be noted that localStorage is unreliable in the browser on mobile devices or in the WebView used by various Native Apps, and may be emptied for various reasons (such as exiting App, network switching, insufficient memory, etc.). SessionStorage, as the name implies, is similar to a session, as soon as you close the browser (including the browser TAB), will be cleared. Due to the short life of sessionStorage, the application scenario is limited, but on the other hand, it is not prone to abnormal situations, relatively reliable.

The data structure

Localstorage is a standard key-value pair (KV) data type, simple but also easy to expand, as long as you want to store the object in localstorage in some encoding way to transform into a string, it can be easily supported. For example, converting an object to a JSON string lets you store the object. Convert the image to DataUrl (Base64) to store the image. In addition, the “key is unique” feature is very important for key-value versus data types, because repeated assignments to the same key overwrite the previous value.

Expiration time

Unfortunately, localstorage does not support setting the expiration time. If you want to set the expiration time, you can only package a layer of logic to achieve:

function set(key,value){
  var curtime = new Date().getTime();// Get the current time
  localStorage.setItem(key,JSON.stringify({val:value,time:curtime}));// Convert to a JSON string sequence
}
function get(key,exp) / /expIs the set expiration time{
  var val = localStorage.getItem(key);// Get the stored element
  var dataobj = JSON.parse(val);// Parse out the JSON object
  if(new Date().getTime() - dataobj.time > exp)// If the current time - minus the time set at creation time of the stored element > expiration time
  {
    console.log("expires");// Expiration prompt
  }
  else{
    console.log("val="+dataobj.val); }}Copy the code

Capacity limits

At present, the industry is basically unified as 5M, which is much larger than the 4K of cookies. Please save your time to use it.

Domain name limit

Due to the security policy of the browser, localstorage is not cross-domain, nor can it let the child domain name inherit the parent domain name localstorage data, which is quite a big difference with cookies.

Exception handling

Localstorage in the current browser environment, is not completely stable, there may be a variety of bugs, must consider exception handling. I personally believe that localstorage is only a means of resource localization optimization, not because of the use of localstorage to reduce the availability of the program, that is just in the console output error message exception handling I am absolutely opposed. Localstorage usually uses try/catch to catch exceptions.

How can I test whether the current browser supports LocalStorage

The current common practice is to check whether window.localstorage exists, but some browsers have bugs. Although localStorage is “supported”, low-level bugs such as the inability to setItem() may even occur in the actual process. Therefore, I recommend that you use a try/catch structure to determine whether the browser supports localstorage by setting /get a test data.

Browser compatibility

| Feature | Chrome | Firefox | Internet Explorer | Opera | Safari | Android |Opera Mobile|Safari Mobile| | ————- | | localStorage | | | 3.5 4 8 11 | | | | | 2.1 4 10.50 iOS 3.2 | | sessionStorage 5 | | 2 | | | | | 2.1 4 10.50 8 11 | | iOS 3.2

How to debug

You can view localstorage data under the current domain name in the Resources-Local Storage and Resources-Session Storage panels in chrome Developer Tools.

Cannot repeat setItem() on ios devices

In addition, setItem() on iPhone/iPad sometimes causes a weird QUOTA_EXCEEDED_ERR error, so removeItem() is usually ok before setItem.

Related plug-ins

  • store.js
  • mozilla/localForage
  • localFont

Refer to the article

  • W3C – Web Storage
  • HTML5 LocalStorage LocalStorage
  • MDN – Window.localStorage