HTML5 local storage and HTML5 Storage

Source: Internet
Author: User

HTML5 local storage and HTML5 Storage

From http://diveintohtml5.info/storage.html

 

What is HTML5 storage?

Simply put, it is a way to make the web page locally store key-value pairs on the browser side. Like cookies, even if you navigate from a website to another website, you close the tab page of the browser and exit the browser, the data still exists. Unlike cookies, data will never be sent to a remote server.

 

Example: Check whether HTML5 storage exists

Write your own code

function supports_html5_storage() {  try {    return 'localStorage' in window && window['localStorage'] !== null;  } catch (e) {    return false;  }}

Use Modernizr

if (Modernizr.localstorage) {  // window.localStorage is available!} else {  // no native support for HTML5 storage :(  // maybe try dojox.storage or a third-party solution}

 

How to Use HTML5 to store data?

HTML5 storage is based on key/value pairs. data is stored based on the key and then retrieved based on the key.

  • Key: string type.
  • Value: Any types supported by JavaScript, including strings, Booleans, integers, and floats.

However, the value is actually stored as a string, so if you want to store any data other than the string type, you need to useparseInt()OrParseFloat () function to forcibly convert the type.

 

Storage Interface

Storage interface getItem (), setItem ()

interface Storage {  getter any getItem(in DOMString key);  setter creator void setItem(in DOMString key, in any data);};

When setItem () is called, the existing key will overwrite the content of the previous value. When getItem () is called, null will be returned if a non-existing key is used.
Like other JavaScript objects, you can treat localStroage objects as an associated array and use square brackets to replace getItem () and setITem ():

var foo = localStorage.getItem("bar");// ...localStorage.setItem("bar", foo);

It can be replaced with square brackets:

var foo = localStorage["bar"];// ...localStorage["bar"] = foo;

 

RemoveItem (), clear () of the Storage Interface ()

interface Storage {  deleter void removeItem(in DOMString key);  void clear();};

When removeItem () is called, it does not work if the key does not exist.

 

Storage interface length attribute, the name of each key

interface Storage {  readonly attribute unsigned long length;  getter DOMString key(in unsigned long index);};

If you call key () But index is not in the range of (0-(length-1), the function returns null.

 

In addition, HTML supports up to 5 MB local storage.QUOTA_EXCEEDED_ERR"Exception, and you cannot apply for a new bucket.

 

How can I track changes to the HTML5 storage area?

If you want to use code to track when the storage region has changed, you can capture storage events. Whether setItem (), removeItem (), or clear () is called, the storage event is triggered as long as a change occurs.

Storage events are supported in any region that supports localStorage. This includes IE8 that does not support W3C standard addEventListener. To hook this storage event, you need to check the event mechanism supported by the browser.

Like capturing other events, you can also use jQuery or other JavaScript libraries to register event handlers.

if (window.addEventListener) {  window.addEventListener("storage", handle_storage, false);} else {  window.attachEvent("onstorage", handle_storage);};

The handle_storage callback function is called and passed in a StorageEvent object, except that the IE event object is stored in window. event.

function handle_storage(e) {  if (!e) { e = window.event; }}

At this point, the variable e becomes a StorageEvent object and has the following useful attributes:

Attribute Type Description
Key String Name of the key to be added, removed, or modified
OldValue Any The previous value (already overwritten). If it is a newly added item, it is null.
NewValue Any New value. If it is removed, it is null.
Url */uri * String Call method trigger change page

The storage event cannot be canceled.

 

HTML5 practice

Save the game status:

function saveGameState() {    if (!supportsLocalStorage()) { return false; }    localStorage["halma.game.in.progress"] = gGameInProgress;    for (var i = 0; i < kNumPieces; i++) {    localStorage["halma.piece." + i + ".row"] = gPieces[i].row;    localStorage["halma.piece." + i + ".column"] = gPieces[i].column;    }    localStorage["halma.selectedpiece"] = gSelectedPieceIndex;    localStorage["halma.selectedpiecehasmoved"] = gSelectedPieceHasMoved;    localStorage["halma.movecount"] = gMoveCount;    return true;}

Restore the game status:

function resumeGame() {    if (!supportsLocalStorage()) { return false; }    gGameInProgress = (localStorage["halma.game.in.progress"] == "true");    if (!gGameInProgress) { return false; }    gPieces = new Array(kNumPieces);    for (var i = 0; i < kNumPieces; i++) {    var row = parseInt(localStorage["halma.piece." + i + ".row"]);    var column = parseInt(localStorage["halma.piece." + i + ".column"]);    gPieces[i] = new Cell(row, column);    }    gNumPieces = kNumPieces;    gSelectedPieceIndex = parseInt(localStorage["halma.selectedpiece"]);    gSelectedPieceHasMoved = localStorage["halma.selectedpiecehasmoved"] == "true";    gMoveCount = parseInt(localStorage["halma.movecount"]);    drawBoard();    return true;}

 

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.