Detailed description of the usage of localStorage in JavaScript, and detailed description of localstorage

Source: Internet
Author: User

Detailed description of the usage of localStorage in JavaScript, and detailed description of localstorage

LocalStorage is mainly used to replace cookies and solve the read/write difficulties and limited capacity problems of cookies (refer to the usage points of cookies.

LocalStorage has the following features:

1. localStorage is a common object. Any object operation applies.

2. the attribute value of the localStorage object can only be a string.

This requires special attention. If we want to save an object to localStorage, We can splice it. For example

Var obj = {"na = me": "chua", age: 9} // splice it to localStoragevar str = ""; for (var I in obj) {str + = encodeURIComponent (I) + "=" + encodeURIComponent (obj [I]) + ";"} str = str. substring (0, str. length-1); localStorage. testObj = str; // parsed var strA = localStorage. testObj. split (";"); var newObj ={}; for (var I = 0; I <strA. length; I ++) {var tmp = strA [I]. split ("="); newObj [decodeURIComponent (tmp [0])] = decodeURIComponent (tmp [1]);}

Of course, you can also use the JSON class to convert the object into a string and save it. Then, convert the json string to a truly available json object format.

3. The default space size supported by localStorage is 5 MB, and the support for modern browsers is good.

Use the cutting graph of the HTML5 LocalStorage local storage of xiaowei0705

The customer's home reminds everyone to note that it is necessary to enable memory space support in the background when using the mobile phone.

"QUOTA_EXCEEDED_ERR" is an exception. If your storage capacity exceeds the limit (5 MB), this exception is reported.

4. localStorage has methods

Add a key-value Pair: localStorage. setItem (key, value)

Obtain the key value: localStorage. getItem (key)

Delete the key-Value Pair: localStorage. removeItem (key ).

Clear all key-value pairs: localStorage. clear ().

Obtain the attribute name (key name): localStorage. key (index) of localStorage ).

There is also an attribute length that is different from that of a common object:

Obtain the number of key-value pairs saved in localStorage: localStorage. length.

The following example is used to obtain the key-value pairs of localStorage.

for(var i=0;i<localStorage.length;i++){console.log(localStorage.key(i)+ " : " + localStorage.getItem(localStorage.key(i)));} 

In line with the principle of believing in the native method, we should try to use the native method to operate localStorage. However, sometimes the QUOTA_EXCEEDED_ERR error occurs when setItem () is called on the iPhone/iPad. The solution is to removeItem () before setItem (). Therefore, from this compatibility issue, it seems that it is more convenient and compatible to add/delete key-value pairs using objects.

5. localStorage event

The storage event of localStorage cannot be canceled in the processing function of the storage event.

The storage event is only a notification sent to you by the browser after the localStorage data changes. Note that the condition here is that the data has actually changed. That is to say, if the current storage region is empty, you will not trigger the event by calling clear. Alternatively, if you use setItem () to set a value that is the same as the existing value, the event will not be triggered. When the storage area changes,This includes many useful attributes:

• StorageArea: indicates the storage type (Session or Local)
• Key: key of the item to be changed
• OldValue: Original Value of the key
• NewValue: New Value of the key
• Url *: the URL where the key changes

Note: The url attribute is a uri attribute in the early standard. Some browsers were released earlier and did not include this change. For compatibility consideration, before using the url attribute, you should first check whether it exists. If there is no url attribute, you should use the uri attribute

PS: it is normal to store and read data in firefox and chrome, but it seems a bit problematic to trigger the storage event. Modifying localStorage in chrome triggers the storage event on this page, after the storage is modified on the Firefox page, the storage event of the window is not triggered, but the same period is a.htmland B .html. In the page, setItem can trigger the storage event of the window on the B page, similarly, setItem on page B can trigger the storage event of window on page. in IE9, the setting value of the page can trigger the storage event of the current page, and the setting value of the current page can also trigger the storage event of other page windows under the same "origin, this seems more appealing. the instance recommends the initial test of PrimeTechBlog: localstorage of WebStorage

Therefore, we recommend that you write compatible processing functions for compatible browsers or by yourself, or you do not need to use storage events.

Instance

If (window. addEventListener) {window. addEventListener ("storage", handle_storage, false);} else {window. attachEvent ("onstorage", handle_storage) ;}; function handle_storage (e) {if (! E) {e = window. event;} // response code section ...}

Some smaller points:

LocalStorage takes effect only when it is accessed by domain name.

If you call the clear () method, both key, oldValue, and newValue are set to null.

Consistent localStorage usage

• LocalStorage-no time limit for data storage
• SessionStorage-data storage for a session

LocalStorage provides the following methods:

1. Storage: localStorage. setItem (key, value)

If the key exists, update the value.

2. Obtain: localStorage. getItem (key)

If the key does not exist, null is returned.

3. Delete: localStorage. removeItem (key)

Once deleted, all data corresponding to the key will be deleted.

4. clear all: localStorage. clear ()

In some cases, using removeItem to delete objects one by one is too troublesome. You can use clear to clear the data stored in all localStorage objects.

5. traverse the keys stored in localStorage

. Length total data, for example, localStorage. length
. Key (index) to obtain the key, for example, var key = localStorage. key (index );

6. store data in JSON format

JSON. stringify (data) converts an object into a JSON data string and returns the converted string.
JSON. parse (data) parses the data into an object and returns the parsed object.

Note: Data stored in localStorage cannot be shared across browsers. A browser can only read data from its own browsers, with a storage space of 5 MB.

Articles you may be interested in:
  • How to Use jquery to read the value of html5 localstorage
  • How to implement local cache using JS localStorage
  • Number of Characters in the string calculated by Javascript in localStorage

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.