神刀安全网

A Bigger, Better Cookie: Using the HTML5 Web Storage API

For the longest time – most of the web’s teenage years – information from a website could only be stored on theclient side using acookie. Like the nutrition of most teenagers, cookies were an incomplete answer to the problems of client-side storage, while also being tricky to wrangle inJavaScript.

In the last five years, the web has grown up significantly. Part of that has includedHTML5 client-side storage of data, in the form of the Web Storage API, which eliminates most of the previous limitations of cookies.

Similarities and Differences

Like cookies, the Web Storage API may store information temporarily or “permanently”:

  • for temporary use, the sessionStorage property retains information so long as the browser is kept running . When the user quits the browser, the information is lost.
  • for “permanent” use, we employ localStorage .

This article will concentrate on the (arguably more useful and well-known) localStorage aspect of the Web Storage API.

Simple Storage

The localStorage property takes a key and a value . There are three ways of writing a value using localStorage :

localStorage.decision = "east"; localStorage["decision"] = "east"; localStorage.setItem("decision", "east");

In the example above, decision is the key, and east is the value. All three techniques are equivalent. To retrieve the value, we can use (in theconsole):

localStorage.decision > 'east'  localStorage["decision"] > 'east'  localStorage.getItem("decision") > 'east'

localStorage always storesstrings, meaning that integers and otherdata types must be converted into strings for storage.

Aside from ease of use, the Web Storage API has a number of significant advantages over cookies:

  • There is a limit of 5MB per origin for data in localStorage , compared to the 3KB of cookies (note that users can alter the maximum storage size for data in their browser, so this space is not completely guaranteed; it can also be altered with the Quota Management API ).
  • cookie data has to be transferred in a HTTP request, and read with another request; localStorage can be written and read at any time.
  • cookie data is stored in a single string, which can make parsing the data challenging. As we have seen, localStorage uses a very readable key and value system, of which you can have as many as you wish.

Choose Your Own Adventure

As an example, let’s say that we were building a simple adventure game, similar to “Choose Your Own Adventure” books or the first computer text adventures. Each decision made in the adventure will take you to a new page. The first page offers two options:

<p> > West of House <p>You are standing in an open field west of a white house,  with a boarded front door. <p>There is a small mailbox here. You can proceed <a href='north.html'>north</a> or <a href='south.html'>south</a>

Our adventurer will proceed through a series of linked and branching pages with each decision they make, but we want to remember the first choice they made. To do so, we’ll write their decision to localStorage . At the bottom of the first page, add a script:

<script> var decisionLinks = document.getElementsByTagName('a'); for (var i = 0; i < decisionLinks.length; i++) {     decisionLinks[i].addEventListener('click', function(e) {         localStorage.decision = e.target.textContent;     }); } </script>

This script gathers up all the links on the page, attaching an event listener to each that records the text in the link in localStorage before proceeding to the linked page.

Adventurer’s End

Later in our adventure, we want to check the user’s initial choice. On some other page on our site, we present default text:

<p id="conclusion">As you enter the barrow, the door closes  inexorably behind you. The night is dark and full of terrors. 

For entirely arbitrary reasons, we want the player to die on this page if they first proceeded north on their adventure. At the bottom of the page, add a script:

<script> var conclusion = document.getElementById('conclusion'); if (localStorage.decision == 'north') {     conclusion.insertAdjacentHTML('beforeend', ' You have been eaten by a grue.'); } </script>

If the adventurer first went north, the if decision will evaluate to true , and the user will be eaten; if they start over again, localStorage will be reset with the new decision they make, potentially altering the life-changing consequences when they reach the final page with insertAdjacentHTML .

Choice Matters

The Web Storage API has excellent browser support: every browser supports both localStorage and sessionStorage , including IE8 and up. Given it’s advantages over cookies, there are few reasons to go with the traditional system, unless you want the reliability of PHP… but even then, the cookie could be blocked or erased by the client. For storing data on the client, sessionStorage is an excellent choice.

Photograph byMatt DeTurck, licensed under Creative Commons

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » A Bigger, Better Cookie: Using the HTML5 Web Storage API

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址