Explain the use of localstorage in JavaScript _javascript tips

Source: Internet
Author: User
Tags delete key response code time limit

Localstorage is mainly used as a substitute for cookies, which solves the problem of poor reading and writing and limited capacity of cookies (reference cookies are used).

Localstorage has the following several characteristics

1.localStorage is a normal object, and the operation of any object is applicable.

The property value of a 2.localStorage object can only be a string.

This requires special attention, assuming that we want to save an object into the Localstorage, you can use the splicing method. Such as

var obj = {
"na=me": "Chua",
age:9
}
//stitching to localstorage
var str = "";
for (var i in obj) {
str = encodeuricomponent (i) + "=" + encodeURIComponent (Obj[i]) + ";"
}
str = str.substring (0,str.length-1);
Localstorage.testobj = str;
Parse out
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 an object to a string, and then convert the JSON string to a truly available JSON object format when you take it out.

3.localStorage supports a default space size of 5 m, modern browser support good

Borrowing xiaowei0705 's HTML5 localstorage local storage Chettu

The cloud-dwelling community reminds you of the need to focus on the use of mobile phones in the background to open up memory space support.

"Quota_exceeded_err" is an exception, if you use more storage capacity than the limit (5M) will report this exception

4.localStorage itself comes with a method

Add key value pairs: Localstorage.setitem (Key,value)

Get key value: Localstorage.getitem (Key)

Delete key value pairs: Localstorage.removeitem (key).

Clears all key-value pairs: localstorage.clear ().

Gets the property name (key name) of the Localstorage: Localstorage.key (Index).

There is also a property length that is not the same as a normal object:

Gets the number of key-value pairs saved in the localstorage: Localstorage.length.

The following example is used to get the key value pairs of the Localstorage

for (Var i=0;i<localstorage.length;i++) {
Console.log (Localstorage.key (i) + ":" + localstorage.getitem ( Localstorage.key (i)));

In the principle of believing in native methods, we should try to use native methods to operate localstorage. However, there are sometimes strange quota_exceeded_err errors when calling SetItem () on Iphone/ipad. The solution is to RemoveItem () before SetItem. So from this compatibility point of view, it appears that using object Add/Remove key value is more convenient, and more compatible.

5.localStorage Event

Localstorage Storage event, which cannot be canceled in the handler function of the stored event.

A storage event is just a notification that the browser gives you after the Localstorage data has changed. Notice that the condition here is that the data really changed. In other words, if the current storage area is empty, you can call clear () without triggering the event. Or you can set a value that is the same as an existing value by SetItem (), and the event will not be triggered. When the storage area changes, it is triggered, which contains a number of useful properties:

Storagearea: Represents a storage type (session or local)
key: Key that has changed
Oldvalue:key's original value
New value for Newvalue:key
url*: The URL where key changes occur

Note: The URI attribute is in the early specification of the URL property. Some browsers were released earlier and did not include this change. For compatibility reasons, you should check for the existence of the URL property before using it, and if there is no URL attribute, you should use the URI attribute

PS: It is normal to store and read in Firefox and Chrome, but there seems to be a problem with the triggering of the storage event, and the chrome modification localstorage can trigger the storage event on this page, Firefox Self-page modification storage did not trigger window storage events, but also access to a.html and b.html, in a page SetItem can trigger the window in page B storage events, The same SetItem on page B can trigger the storage event of window on page A. In IE9, the setting value of the page itself triggers the storage event of the current page, and the same setting value of the current page triggers the storage event of the other page window under the same "origin". It seems to make more sense. Examples recommend Primetechblog's preliminary webstorage localstorage

Therefore, it is recommended that you write compatible processing functions for compatible browsers, or simply not 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 small points:

Localstorage to access through the domain name to work

If the clear () method is invoked, the key, OldValue, and NewValue are all set to NULL.

Localstorage used in the same way

localstorage-No time limit for data storage
sessionstorage-Data storage for a session

Localstorage provides several methods:

1, Storage: Localstorage.setitem (Key,value)

If key exists, update value

2, Get: Localstorage.getitem (Key)

Returns NULL if key does not exist

3, Delete: Localstorage.removeitem (key)

Once deleted, key data will be deleted

4, All clear: Localstorage.clear ()

Sometimes using RemoveItem to remove too much trouble, you can use clear, the effect is to erase all Localstorage objects saved data

5, traversing the Localstorage storage key

. length data Total, example: localstorage.length
. Key (Index) gets key, example: Var key=localstorage.key (index);

6. Storing JSON format data

Json.stringify (data) converts an object into a JSON-formatted string, returning the converted string
Json.parse data to parse the object, returning the parsed object

Note: Localstorage data can not be shared across the browser, a browser can only read the data of their respective browsers, storage space 5M.

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.