HTML5 local Storage (localstorage) Usage Introduction

Source: Internet
Author: User
Tags sessionstorage

1, HTML5 several storage forms
Local Storage (localstorage && sessionstorage)
Offline cache (application cache)
IndexedDB and Websql
2, Localstorage && sessionstorage
Expiry time: localstorage permanent storage, never expires unless manually deleted
Sessionstorage when the browser is reopened, it disappears.
Size: Each domain name is 5M
3. Localstorage API and Sessionstorage API are consistent
GetItem//Fetch Records
setiten//Setting record
removeitem//Removing records
key//the value corresponding to the key
clear//Clearing Records
4. Stored content
arrays, images, JSON, styles, scripts ... (only content that can be serialized into strings can be stored)
5. Localstorage instances

<!DOCTYPE><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8" /><Metahttp-equiv= "Access-control-allow-origin"content= "Anonymous"><title>Locstorage Picture Storage</title></Head><Body></Body></HTML><Script>   varsrc='Images/1.png';//This must be run on the server, picture if the current server picture! functionSet (key) {varimg=Document.createelement ('img');//Create a picture elementImg.addeventlistener ('Load',function() {//Bind load timevarImgcavens=Document.createelement ('Canvas'); Imgcontent=Imgcavens.getcontext ('2d'); Imgcavens.width=  This. width;//set the canvas size to the size of the picture itself Imgcavens.height=  This. Height; Imgcontent.drawimage ( This,0,0, This. Width, This. Height); varImgasdataurl=Imgcavens.todataurl ('Image/png');//This method must be run on the server
/*
After making changes to the image data, you can use the Todataurl method to re-convert the canvas data into a generic image file format.
function Convertcanvastoimage (canvas) {
var image = new Image ();
IMAGE.SRC = Canvas.todataurl ("Image/png");
return image;
}
The above code translates the canvas data into a PNG data URI.
*/
Try{Localstorage.setitem (key,imgasdataurl);//Save Picture Address }Catch(e) {Console.log ("Storagefaild:"+e);//Error message}},false) Img.src=src;//Specify the image address to store}functionget (key) {varSrcstr=Localstorage.getitem (key);//Gets the locally stored elementvarimgobj=Document.createelement ('img'); IMGOBJ.SRC=srcstr;//Specify Picture path Document.body.appendChild (imgobj);//Add element to page}</Script>

The above methods can be run in Firefox and Chrome, running examples

We now look at how the resources are stored,

At this point in any case to refresh the page and reopen the browser, just stored pictures are there, unless manually deleted!

6. Locstorage Expiration Policy

Since HTML5 does not set an expiration policy for local storage, it is possible to write its own expiration policy program when processing an expiration policy for a picture, as follows:

<!DOCTYPE><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8" /><Metahttp-equiv= "Access-control-allow-origin"content= "Anonymous"><title>Locstorage Expiration Policy</title></Head><Body></Body></HTML><Script>functionSet (key,value) {varCurtime= NewDate (). GetTime ();//Get Current time Localstorage.setitem (Key,json.stringify ({val:value,time:curtime}));//Convert to JSON string sequence
/*
Description
JSON. Parse is used to parse a JSON object from a string, such as
var str = ' {' name ': ' Huangxiaojian ', ' age ': ' 23 '} '
Results:
Json.parse (str)
Object
Age: "23"
Name: "Huangxiaojian"
__PROTO__: Object
Note: Single quotes are written in {}, each property name must be in double quotation marks, or an exception will be thrown.
JSON. Stringify () is used to parse out a string from an object, such as
var a = {A:1,b:2}
Results:
Json.stringify (a)
"{" A ": 1," B ": 2}"
*/
}functionget (KEY,EXP)//exp is the set expiration time {varVal=Localstorage.getitem (key);//Gets the stored elementvarDataobj=Json.parse (val);//Parse out JSON objectif(NewDate (). GetTime ()-Dataobj.time>exp)//If the current time-minus the stored element is set at the time of creation > Expiration Time {console.log ("Expires");//Prompt expires}Else{Console.log ("val="+dataobj.val);}}</Script>

Use the action as shown in:

Look at the results of local storage

The simple example above can operate HTML5 local storage function, feel HTML5 in the local storage aspect is very convenient!

HTML5 local Storage (localstorage) Usage Introduction

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.