Note: DOM Storage is not the same as mozStorage (Mozilla's XPCOM interfaces to SQLite) or the Session store API (an XPCOM storage utility for use by extensions).

Note: This article will soon be getting refactored substantially to split up its contents into the various storage APIs, instead of having them all here in one page. A separate article guiding through the various APIs will be provided as well.

Description

The DOM Storage mechanism is a means through which string key/value pairs can be securely stored and later retrieved for use. The goal of this addition is to provide a comprehensive means through which interactive applications can be built (including advanced abilities, such as being able to work "offline" for extended periods of time).

Mozilla-based browsers, Internet Explorer 8+, Safari 4+, and Chrome all provide a working implementation of the DOM Storage specification. (In case you need this functionality cross-browser and you need to cater for older versions of IE, it may be useful to note that IE also has a similar legacy feature called "userData behavior" that pre-dates the addition of DOM Storage to IE in IE8.)

DOM Storage is useful because no good browser-only methods exist for persisting reasonable amounts of data for any period of time. Browser cookies have limited capacity and provide no support for organizing persisted data, and other methods (such as Flash Local Storage) require an external plugin.

One of the first public applications to make use of the new DOM Storage functionality (in addition to Internet Explorer's userData Behavior) was halfnote (a note-taking application) written by Aaron Boodman. In his application, Aaron simultaneously saved notes back to a server (when Internet connectivity was available) and a local data store. This allowed the user to safely write backed-up notes even with sporadic Internet connectivity.

While the concept, and implementation, presented in halfnote were comparatively simple, halfnote's creation shows the possibility for a new breed of web applications that are usable both online and offline.

Reference

The following are global objects that exist as properties of every window object. This means that they can be accessed as sessionStorage or window.sessionStorage. (This is important because you can then use IFrames to store, or access, additional data beyond what is immediately included in your page.)

Storage

This is a constructor (Storage) for all Storage instances (sessionStorage and globalStorage[location.hostname]). Setting Storage.prototype.removeKey = function(key){ this.removeItem(this.key(key)) } would be accessed as localStorage.removeKey and sessionStorage.removeKey.

globalStorage items are not an instance of Storage, but instead are an instance of StorageObsolete.

Note: Although the values can be set and read using the standard JavaScript property access method, using the getItem and setItem methods is recommended.

Note: Keep in mind that everything you store in any of the storages described in this page is converted to string using its .toString method before being stored. So trying to store a common object will result in string "[object Object]" to be stored instead of the object or its JSON representation. Using native JSON parsing and serialization methods provided by the browser is a good and common way for storing objects in string format.

sessionStorage

This is a global object (sessionStorage) that maintains a storage area that's available for the duration of the page session. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated.

The sessionStorage object is most useful for hanging on to temporary data that should be saved and restored if the browser is accidentally refreshed.

Examples:

Autosave the contents of a text field, and if the browser is accidentally refreshed, restore the text field contents so that no writing is lost.

// Get the text field that we're going to track
var field = document.getElementById("field");
// See if we have an autosave value
// (this will only happen if the page is accidentally refreshed)
if ( sessionStorage.getItem("autosave")) {
// Restore the contents of the text field
field.value = sessionStorage.getItem("autosave");
}
// Check the contents of the text field every second
setInterval(function(){
// And save the results into the session storage object
sessionStorage.setItem("autosave", field.value);
}, 1000);

localStorage

localStorage is the same assessionStoragewith same same-origin rules applied but it is persistent. localStorage was introduced in Firefox 3.5.

Note: When the browser goes into private browsing mode, a new, temporary database is created to store local storage data; this database is emptied and thrown away when private browsing mode is turned off.

Compatibility

Storage objects are a recent addition to the standard. As such they may not be present in all browsers. You can work around this by inserting one of the following two codes at the beginning of your scripts, allowing use of localStorage object in implementations which do not natively support it.

This algorithm is an exact imitation of the localStorage object, but makes use of cookies.

Note: The maximum size of data that can be saved is severely restricted by the use of cookies. With this algorithm, use the functions localStorage.setItem() and localStorage.removeItem() to add, change, or remove a key. The use of methods localStorage.yourKey = yourValue; and delete localStorage.yourKey; to set or delete a key is not a secure way with this code. You can also change its name and use it only to manage a document's cookies regardless of the localStorage object.

Note: By changing the string "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/" to: "; path=/" (and changing the object's name), this will become a sessionStorage polyfill rather than a localStorage polyfill. However, this implementation will share stored values across browser tabs and windows (and will only be cleared when all browser windows have been closed), while a fully-compliant sessionStorage implementation restricts stored values to the current browsing context only.

Here is another, less exact, imitation of the localStorage object. It is simpler than the previous one, but it is compatible with old browsers, like Internet Explorer < 8 (tested and working even in Internet Explorer 6). It also makes use of cookies.

Note: The maximum size of data that can be saved is severely restricted by the use of cookies. With this algorithm, use the functions localStorage.getItem(), localStorage.setItem(), and localStorage.removeItem() to get, add, change, or remove a key. The use of method localStorage.yourKey in order to get, set, or delete a key is not permitted with this code. You can also change its name and use it only to manage a document's cookies regardless of the localStorage object.

Note: By changing the string "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/" to: "; path=/" (and changing the object's name), this will become a sessionStorage polyfill rather than a localStorage polyfill. However, this implementation will share stored values across browser tabs and windows (and will only be cleared when all browser windows have been closed), while a fully-compliant sessionStorage implementation restricts stored values to the current browsing context only.

Compatibility and relation with globalStorage

localStorage is also the same as globalStorage[location.hostname], with the exception of being scoped to an HTML5 origin (scheme + hostname + non-standard port) and localStorage being an instance of Storage as opposed to globalStorage[location.hostname] being an instance of StorageObsolete which is covered below. For example, http://example.com is not able to access the same localStorage object as https://example.com but they can access the same globalStorage item. localStorage is a standard interface while globalStorage is non-standard so you shouldn't rely on these.

Please note that setting a property on globalStorage[location.hostname] does not set it on localStorage and extending Storage.prototype does not affect globalStorage items; only extending StorageObsolete.prototype does.

globalStorage

Non-standard
This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

Obsolete since Gecko 13.0 (Firefox 13.0 / Thunderbird 13.0 / SeaMonkey 2.10)This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.

globalStorage is obsolete since Gecko 1.9.1 (Firefox 3.5) and unsupported since Gecko 13 (Firefox 13). Just uselocalStorageinstead. This proposed addition to HTML5 has been removed from the HTML5 specification in favor oflocalStorage, which is implemented in Firefox 3.5. This is a global object (globalStorage) that maintains multiple private storage areas that can be used to hold data over a long period of time (e.g., over multiple pages and browser sessions).

Note: globalStorage is not a Storage instance, but a StorageList instance containing StorageObsolete instances.

// Save data that only scripts on the mozilla.org domain can access
globalStorage['mozilla.org'].setItem("snippet", "<b>Hello</b>, how are you?");

Specifically, the globalStorage object provides access to a number of different storage objects into which data can be stored. For example, if we were to build a web page that used globalStorage on this domain (developer.mozilla.org) we'd have the following storage object available to us:

globalStorage['developer.mozilla.org'] - All web pages within the developer.mozilla.org sub-domain can both read and write data to this storage object.

Examples:

All of these examples require that you have a script inserted (with each of the following code) in every page that you want to see the result on.

Remember a user's username for the particular sub-domain that is being visited:

globalStorage['developer.mozilla.org'].setItem("username", "John");

Keep track of the number of times that a user visits all pages of your domain:

// parseInt must be used since all data is stored as a string
globalStorage['mozilla.org'].setItem("visits", parseInt(globalStorage['mozilla.org'].getItem("visits") || 0 ) + 1);

Doesn't show up in the "Tools -> Options -> Advanced -> Network -> Offline data" list, unless the site also uses the offline cache. If the site does appear in that list, its DOM storage data is removed along with the offline cache when clicking the Remove button.

jData - A shared localStorage object interface that can be accessed by any website on the internet and works on Firefox 3+, Webkit 3.1.2+ nightlies, and IE8. Think of it as pseudo-globalStorage[""] but write access needs user confirmation.

HTML5 localStorage example - Very simple and easy to understand example of localStorage. Saves and retrieves texts and shows a list of saved items. Tested in Firefox 3 or higher.

HTML5 Session Storage - A very simple example of session storage. Also includes a example on local storage. Tested in Firefox 3.6 or higher.

Basic DOMStorage Examples - Broken in Firefox 3 and up due to use of globalStorage on one domain level up from the current domain which is not allowed in Firefox 3.