Html5 Local Storage

Source: Internet
Author: User
Tags sessionstorage

Html5 Local Storage

1. html5 storage formats

Local Storage (localStorage & sessionStorage)

Application cache)

IndexedDB and webSQL

2. localStorage & sessionStorage

Expiration time: localStorage is permanently stored and never expires unless it is manually deleted

SessionStorage disappears after the browser is re-opened.

Size: each domain name is 5 MB

3. The localStorage API and sessionStorage API are consistent.

GetItem // retrieve record
SetIten // set the record
RemoveItem // remove record
Key // obtain the value corresponding to the key
Clear // clear records

4. stored content

Array, image, json, style, script... (Any content that can be serialized into strings can be stored)

5. localStorage instance

Copy the content to the clipboard using JavaScript Code
  1. <! DOCTYPE>
  2. <Head>
  3. <Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
  4. <Meta http-equiv = "Access-Control-Allow-Origin" content = "anonymous">
  5. <Title> locstorage </title>
  6. </Head>
  7. <Body>
  8. </Body>
  9. </Html>
  10. <Script>
  11. Var src = 'images/1.png '; // you must run the image on the server!
  12. Function set (key ){
  13. Var img = document. createElement ('img '); // create an image Element
  14. Img. addEventListener ('load', function () {// bind the loading time
  15. Var imgcavens = document. createElement ('canvas ');
  16. Imgcontent = imgcavens. getContext ('2d ');
  17. Imgcavens. width = this. width; // set the canvas size to the image size.
  18. Imgcavens. height = this. height;
  19. Imgcontent. drawImage (this, 0, 0, this. width, this. height );
  20. Var imgAsDataUrl = imgcavens. toDataURL ('image/png '); // This method must be run on the server/* after the image data is modified, you can use the toDataURL method, reconvert Canvas data into a normal image file format. Function convertCanvasToImage (canvas) {var image = new Image (); image. src = canvas. toDataURL ("image/png"); return image;} the code above converts Canvas data to PNG data URI. */Try {
  21. LocalStorage. setItem (key, imgAsDataUrl); // Save the image address
  22. } Catch (e)
  23. {
  24. Console. log ("storageFaild:" + e); // error message
  25. }
  26. }, False)
  27. Img. src = src; // specify the image address to store
  28. }
  29. Function get (key ){
  30. Var srcStr = localStorage. getItem (key); // obtain locally stored Elements
  31. Var imgobj = document. createElement ('img ');
  32. Imgobj. src = srcStr; // specifies the image path.
  33. Document. body. appendChild (imgobj); // Add an element to the page
  34. }
  35. </Script>

The above method can be run in Firefox and chrome.


 
Now let's take a look at how the resources are stored,
 


At this time, no matter how you refresh the page or re-open the browser, the stored images exist, unless you manually delete them!

6. locstorage expiration Policy

Because html5 does not set an expiration Policy for the local storage, you can write your own expiration policy program when processing the image expiration Policy, as shown below:

Copy the content to the clipboard using JavaScript Code
  1. <! DOCTYPE>
  2. <Head>
  3. <Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
  4. <Meta http-equiv = "Access-Control-Allow-Origin" content = "anonymous">
  5. <Title> locstorage expiration Policy </title>
  6. </Head>
  7. <Body>
  8. </Body>
  9. </Html>
  10. <Script>
  11. Function set (key, value ){
  12. Var curtime = new Date (). getTime (); // get the current time
  13. LocalStorage. setItem (key, JSON. stringify ({val: value, time: curtime}); // converts the string to a json string sequence./* Description: JSON. parse is used to parse json objects from a string, such as var str = '{"name": "huangxiaojian", "age": "23"}'. Result: JSON. parse (str) Object age: "23" name: "huangxiaojian" _ proto __: Object

Note: Each attribute name must be enclosed in double quotation marks ({}). Otherwise, an exception is thrown. JSON. stringify () is used to parse a string from an object, such as var a = {a: 1, B: 2}. Result: JSON. stringify (a) "{" a ": 1," B ": 2 }"*/}

Copy the content to the clipboard using JavaScript Code
  1. Function get (key, exp) // exp is the set expiration time
  2. {
  3. Var val = localStorage. getItem (key); // obtain the stored Element
  4. Var dataobj = JSON. parse (val); // parse the json object
  5. If (new Date (). getTime ()-dataobj. time> exp) // if the current time minus the time when the stored element is created> expiration time
  6. {
  7. Console. log ("expires"); // The system prompts expiration.
  8. }
  9. Else {
  10. Console. log ("val =" + dataobj. val );
  11. }
  12. }
  13. </Script>

The usage is shown in:

View local storage results

The above simple example can be used to operate the html5 local storage function. I feel that html5 is very convenient in local storage!

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.