Web front-end for local storage

Source: Internet
Author: User
Tags http cookie sessionstorage

When we mention the Web front-end local storage, we first need to introduce the concept and history of localized storage. Localized storage has never been a novel concept, because Web applications are always looking to rival or even surpass desktop applications. But the desktop application has always been superior to the Web application because its localized storage has been well supported. For local applications, the operating system provides an abstraction layer for storing and retrieving application-specific data that can be stored in the registry, INI file, or somewhere else, depending on the implementation of the operating system, if the local application requires not only local storage as a key-value pair, You can use an embedded database or a variety of other solutions. And for a Web application, it's local storage is very difficult to go to today's HTML5 local storage step-by-step. To describe its history, we can look at a picture first:

As you can see from the picture, the Web front-end local storage is not easy, both in terms of the size of the data being stored and the compatibility. Before we focus on HTML5 local storage, let's take a look at the concepts of the previous storage methods.

  HTTP Cookie: The disadvantage of HTTP cookies is that it can only store up to 4KB of data, and each HTTP request will be routed back to the server and transmitted in plaintext (unless you use SSL).

  IE userData:userData is a local storage solution introduced by Microsoft in the 90 's browser war, with DHTML's behaviour attribute to store local data, allowing up to 64K of data per page. With up to 640K data per site, UserData's drawbacks are obvious, it's not part of the Web Standard, and it's basically useless unless your program only needs to support ie.

  Flash Cookie: The name of the Flash cookie is somewhat misleading, it is not actually the same as the HTTP cookie, perhaps its name should be called "flash local Storage", flash cookie by default allows each site to store no more than 100K of data, if exceeded, Flash automatically asks users for more storage space, and with Flash's Externalinterface interface, you can easily manipulate Flash's local storage via JavaScript. The problem with Flash is simple, because it's flash.

  Google Gears: Gears is an open source browser plugin released by Google in 07, designed to improve the compatibility of major browsers, gears built-in a sqlite-based embedded SQL database, and provided a unified API to access the database, after obtaining user authorization, Each site can store an unlimited amount of data in a SQL database, and the problem with gears is that Google itself is not using it.

As we can see from the above introduction, the main problem with local storage in the past is that there is a need for specific plug-in support for a larger storage capacity, and for storage methods that do not require plug-in support, are throttled by security issues or size limits. In the face of this double contradiction, HTML5 local storage turned out to be a great boon for front-end developers.

The so-called HTML5 local storage is more accurate to say that the DOM is stored. Based on the definition of MDN, the mechanism for DOM storage is to provide a secure way to access it by storing key/value pairs of string types. The goal of this additional feature is to provide a comprehensive approach that can be used to create interactive applications, including those that are advanced, such as those that can be worked offline for a period of time.

HTML5 's DOM storage is divided into two types: Sessionstorage and Localstorage. Compatibility in contemporary browsers is as follows:

The globalstorage mentioned in the

is non-standard and obsolete, where we ignore it directly. Sessionstorage and Localstorage have been well supported in most modern browsers, but most of them have to take care of browsers that do not support these two objects. In order to detect whether the browser supports these two objects, we can simply use the following code to detect:

 1  function   Storagesupport () { 2  try   { 3  return  ' localstorage ' in  window && window[' localstorage ']!== Span style= "color: #0000ff;"  >null  ;  4 } catch   (e) { 5  return  false  ;  6  }  7 } 

Fortunately, both of these objects are very simple to use, which is borrowed from a graph on the Web:

First, let's take a look at Sessionstorage, a sessionStorage global object that maintains the storage space that is valid during a page session. The page session cycle lasts as long as the browser is open. Page sessions also persist when the page is re-loaded (reload) or restored (restores). A new session is initialized for each new page opened in a new tab or in a new window. This sentence looks more abstract, we look directly at a demo:

1 var name = Sessionstorage.setitem ("MyName", "YUANZM"); 2 alert (Sessionstorage.getitem ("myname"));

When we open in the browser, it will pop up the window, display "YUANZM", and then we press the F12 key to view the browser's debug window:

  

We can find that the key value of "myname" is already in the browser's local storage sessionstorage. This time, refresh the page, still pop up "YUANZM", because if you do not call Sessionstorage.removeitem () or manually clear the item, this item will always exist. The above mentioned " as long as the browser is open, the page session cycle will continue." Page sessions also persist when the page is re-loaded (reload) or restored (restores). Each time a new page is opened in a new tab or in a new window, a new session is initialized " the meaning is that if we do not reset the value of the myname, this value does not exist when a new browser tab is opened or a browser window is opened again, that is, null. To verify this, it's easy to comment out the first line of the above two lines of code, refresh the page, and then open the file in a new browser tab. What is the effect of these two actions respectively? The answer is simple, when you refresh the page again, the "YUANZM" will still pop up, because this data is saved locally, and after the code is changed in the new page open, the result is null, because there is no "myname" value in the current page session.

Next we take a look at Localstorage, he is across multiple windows, and the duration can be more than the current session, meaning when the browser is closed and reopened, the data is still available; With the example above, when the code is changed, the new tab opens the page, the "YUANZM" will still pop up. We look at the effect again in the browser:

  

As these two objects are very simple to use, they are introduced here for the time being. There is a compatibility issue that needs to be covered below. The reason is simple, because not all browsers support both objects. There are two types of compatibility here, the first is in a browser that does not natively support localstorage, and the second is compatible with different browsers for the difference between these two usages. For the first type, the MDN gives the compatible code:

if(!window.localstorage) {object.defineproperty (window,"Localstorage",New(function () {    varAkeys = [], ostorage = {}; Object.defineproperty (Ostorage,"GetItem", {value:function(SKey) {returnSKey? This[SKey]:NULL;}, writable:false, Configurable:false, Enumerable:false    }); Object.defineproperty (Ostorage,"Key", {value:function(Nkeyid) {returnAkeys[nkeyid];}, writable:false, Configurable:false, Enumerable:false    }); Object.defineproperty (Ostorage,"SetItem", {value:function(SKey, svalue) {if(!skey) {return; } Document.cookie= Escape (SKey) + "=" + Escape (svalue) + "; path=/"; }, writable:false, Configurable:false, Enumerable:false    }); Object.defineproperty (Ostorage,"Length", {get:function() {returnAkeys.length;}, Configurable:false, Enumerable:false    }); Object.defineproperty (Ostorage,"RemoveItem", {value:function(SKey) {if(!skey) {return; } varSexpdate =NewDate (); Sexpdate.setdate (Sexpdate.getdate ()-1); Document.cookie= Escape (SKey) + "=; Expires= "+ sexpdate.togmtstring () +"; path=/"; }, writable:false, Configurable:false, Enumerable:false    });  This. get =function () {      varIthisindx;  for(varSKeyinchostorage) {Ithisindx=Akeys.indexof (SKey); if(Ithisindx = = =-1) {Ostorage.setitem (SKey, Ostorage[skey]);} Else{Akeys.splice (ITHISINDX, 1); }        DeleteOstorage[skey]; }       for(Akeys; akeys.length > 0; Akeys.splice (0, 1)) {Ostorage.removeitem (akeys[0]); }       for(varIcouple, IKey, icouplid = 0, Acouples = document.cookie.split (/\s*;\s*/); Icouplid < Acouples.length; icouplid++) {icouple= Acouples[icouplid].split (/\s*=\s*/); if(Icouple.length > 1) {Ostorage[ikey= Unescape (icouple[0])] = unescape (icouple[1]);        Akeys.push (IKey); }      }      returnOstorage;    };  This. Configurable =false;  This. Enumerable =true; })());}
View Code

As for the second, there's a lot of good code on GitHub, and bloggers recommend one of them: GitHub Localstorage

Finally, please reprint the original text, but want to add reprint link: http://www.cnblogs.com/yuanzm/p/4023295.html

Web front-end for local storage

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.