

Going beyond cookies- Using DOM sessionStorage and localStorage to persist larger amounts of info
Date created: Oct 11th, 2010
JavaScript cookies may not have gone the way of staleness yet as a
dependable way of storing and persisting information, but its small size
limit (for most browsers, 4kb per domain) is increasingly an issue. Sure you
can simply store larger amounts of information on the server, but that
burdens the server with additional requests, and more importantly, fails if
you wish your web application to still function when the user is offline. To
better meet the needs of today's web applications, HTML5 busts out two new
ways to store information on the client side- sessionStorage
and
localStorage
(collectively known as DOM Storage). DOM Storage's main
characteristics are:
-
Can store a lot more information than JavaScript cookies. The exact amount varies from browser to browser, but in FF3+, Chrome4+, and Safari4+, it's 5MB per storage area, while in IE8+, it's 10 MB.
-
DOM Storage (
sessionStorage
andlocalStorage
) is supported in the following browsers- FF3.5+, Chrome4+, Safari4+, Opera10.5+, and IE8+. -
For the
sessionStorage
object that's used to store data that persists only through the lifetime of the browser session, it differs from JavaScript cookies in that the data does not persist across browser tabs. The data does survive a browser crash in some browsers, however, such as FF. -
Data stored using DOM Storage, specifically,
localStorage
, do not ever expire automatically.
The DOM Storage objects (sessionStorage
and
localStorage
) all inherit the same set of properties and
methods. They are:
Methods | Description |
---|---|
getItem(key) | Returns a value based on the specified key inside the
DOM Storage area. If no corresponding key exists, null is
returned. |
setItem(key, value) | Stores a string value using the specified key inside the DOM Storage area. If such a key already exists, the previous value stored at that location is replaced with the new one. |
removeItem(key) | Removes a value based on the specified key inside the DOM Storage area. |
key(index) | Returns the key for the content item at the specified index, where index is a zero based integer that corresponds to the position of the item within the DOM Storage area. Note that the position of each item may change as you add or remove items. |
clear() | Clears all data from the DOM Storage area for the current domain. |
properties | |
length | Read-only property that returns the number of items in the DOM Storage area. |
The
window.sessionStorage object
The sessionStorage object is used to store data that should only lasts for the duration of the browser session. The information is retained when reloading or returning to a page within the same browser session:
if (window.sessionStorage){ sessionStorage.setItem("mykey", "Some Value") //store data using setItem() var persistedval=sessionStorage.getItem("mykey") //returns "Some Value" sessionStorage.mykey2="Some Value 2" //store data using the dot notation var persistedval2=sessionStorage.mykey2 //returns "Some Value 2" sessionStorage["mykey3"]="Some Value 3" //store data using the square bracket notation var persistedval3=sessionStorage["mykey3"] //returns "Some Value 3" }
As shown above, values can be set and retrieved using either
getItem()
and setItem()
,
or by directly referencing the key as a property of the object.
While sessionStorage
behaves similarly to JavaScript session
cookies, it is different in the following key ways:
-
The storage limited allotted to each
sessionStorage
area is 5MB (10 MB in IE8), while for cookies, it's 4KB (10KB in IE8). -
Data stored using
sessionStorage
do not persist across browser tabs, even if two tabs both contain webpages from the same domain origin. In other words, data insidesessionStorage
is confined to not just the domain and directory of the invoking page, but the browser tab in which the page is contained in. Contrast that to session cookies, which do persist data from tab to tab. -
In certain browsers such as FF3.5+, data stored using
sessionStorage
will survive a browser crash. This means if a browser is closed due to a crash, the last stored information insidesessionStorage
is still retained when the browser is relaunched.
The following example automatically saves the contents of a
TEXTAREA into sessionStorage
as the user types into it to
rescue the contents in the event of a browser refresh or crash (currently FF3.5+
only). The contents of the following TEXTAREA will survive a hard refresh of
the page, and in the case of supporting browsers, a browser crash as well:
<form> <textarea id="feedback" style="width:350px;height:200px"></textarea><br /> <input type="button" value="Click to Hard Reload Page" onClick="location.reload(true)" /> </form> <script type="text/javascript"> if (window.sessionStorage){ var feedbackarea=document.getElementById("feedback") if (sessionStorage.feedbackdata){ //if there is data stored for the target textarea feedbackarea.value=sessionStorage.feedbackdata //recall it upon refresh or crash } feedbackarea.onkeyup=function(e){ sessionStorage.feedbackdata=this.value //save contents of textarea as user types } } </script>Demo (FF3.5+, Chrome4+, Safari4+, Opera10.5+, or IE8+):
The
window.localStorage object (and window.globalStorage[location.hostname] for FF3.0)
The localStorage
object can be thought of as the persistent
version of sessionStorage
. Whereas the later lasts only for the duration of
a browser tab session, localStorage
persists any saved data indefinitely on
the user's computer and across browser tabs (similar to JavaScript cookies).
The storage size of localStorage
is the same as that for sessionStorage
.
In FF, support for the localStorage
object was
only added starting in FF3.5. In FF3.0 browsers, there exist the
non standard globalStorage[location.hostname]
equivalent object
you can use to maximize browser compatibility. Taking that into account, the below
shows a simple counter that displays the number of times a user has visited
the current page over its history:
<script type="text/javascript"> var mydomstorage=window.localStorage || (window.globalStorage? globalStorage[location.hostname] : null) if (mydomstorage){ var i=(mydomstorage.pagecount)? parseInt(mydomstorage.pagecount)+1 : 1 document.write("You have visited this page <b>" + i + " </b> times altogether.") mydomstorage.pagecount=i } else{ document.write("<b>Your browser doesn't support DOM Storage unfortunately.</b>") } </script>
Demo (requires FF3+, Chrome4+, Safari4+, Opera10.5+, or IE8+):
Creating a
editable to-do list using DOM Storage
Time for something just slightly more ambitious now. Lets
take advantage of the generous space afforded by DOM Storage to create an
editable notepad where users can enter a list of to-do items, with those
items automatically persisted on the user's hard drive, so any changes are
always saved. We make use of HTML5's contenteditable
attribute
to make a DIV's contents editable:
<style type="text/css"> #todolist{ width:200px; height: 200px; font:normal 13px Arial; background:lightyellow; border:1px dashed gray; overflow-y:scroll; padding:5px; } #todolist ol{ margin-left:-15px; } #todolist li{ border-bottom:1px solid gray; margin-bottom:8px; } </style> <body> <div id="todolist" contenteditable="true"> <div contenteditable="false"><b>Edit To-Do List (auto saved):</b></div> <ol> <li>Take out garbage</li> <li>Finish report</li> <li>Set alarm to 6am</li> </ol> </div> <a href="#" onClick="resetlist();return false">Reset To Do List</a> <script type="text/javascript"> var defaulthtml='<div contenteditable="false"><b>Edit To-Do List (auto saved):</b></div>\n' //remember default contents of to-do list defaulthtml+='<ol>\n' defaulthtml+='<li>Take out garbage</li>\n' defaulthtml+='<li>Finish report</li>\n' defaulthtml+='<li>Set alarm to 6am</li>\n' defaulthtml+='</ol>' function resetlist(){ todolistref.innerHTML=defaulthtml domstorage.todolistdata=defaulthtml } var todolistref=document.getElementById("todolist") var domstorage=window.localStorage || (window.globalStorage? globalStorage[location.hostname] : null) if (domstorage){ if (domstorage.todolistdata){ //if there is data stored for the to-do list todolistref.innerHTML=domstorage.todolistdata //recall it } todolistref.onkeyup=function(e){ domstorage.todolistdata=this.innerHTML } } </script>
Demo (FF3.5+, Chrome4+, Safari4+, Opera10.5+, or IE8+):
- Take out garbage
- Finish report
- Set alarm to 6am
Try editing or adding to the list (press enter after the last entry). The contents are automatically saved to DOM Storage each time you press a keystroke.
- Overview of try/catch/finally
- Augmenting DOM Storage with IE's userData Behavior