Channels ▼
RSS

Open Source

HTML5 Web Storage


Checking for Browser Support

The storage area for a given domain is accessed directly from the window object. Therefore, to determine if a user's browser supports the Web Storage API is as easy as checking for the existence of window.sessionStorage or window.localStorage. The following example shows a routine that checks for sessionStorage and localStorage support and displays an alert message about the browser's support for the Web Storage API.


function checkStorageSupport() {

  //sessionStorage
  if (window.sessionStorage) {
    alert('This browser supports sessionStorage');
    
  } else {
    alert('This browser does NOT support sessionStorage');
  }
  
  //localStorage
  if (window.localStorage) {
    alert('This browser supports localStorage');

  } else {
    alert('This browser does NOT support localStorage');
  }
}

Note: Many browsers do not support sessionStorage for files accessed directly from the file system. Make sure you serve up the pages from a web server when you experiment with HTML5 Web Storage.

Setting and Retrieving Values

Let's look at how you can set and retrieve simple values in a page. Setting a value can easily be done in a single statement:


window.sessionStorage.setItem(‘myFirstKey', ‘myFirstValue');

There are three important points to notice from this storage access statement:

  • The object implementing the Web Storage API is attached to the window, so window.sessionStorage contains the functions you need to call.
  • The function we are calling is setItem, which takes a key string and a value string. Although the formal Web Storage API supports passing in non-string values, current browsers are limited in the value types they support.
  • This particular call will set into the session storage the string myFirstValue, which can later be retrieved by the key myFirstKey.

To retrieve the value, you can use the following statement:


alert(window.sessionStorage.getItem(‘myFirstKey'));

Web Storage Events

The HTML5 Web Storage API includes an event mechanism to allow notifications of data updates to be communicated to interested listeners. Web Storage events fire on the window object for every window of the same origin as the storage operation, regardless of whether or not the listening window is doing any storage operations itself.

To register to receive the storage events of a window's origin, simply register an event listener. For example:


window.addEventListener("storage", displayStorageEvent, true);

As you can see, the name "storage" indicates interest in storage events. Any time a Storage object -- either sessionStorage or localStorage -- for that origin is raised any registered event listener will receive the storage event as the specified event handler. The StorageEvent object will be the first object passed to the event handler, and it contains all the information necessary to understand the nature of the storage change.

  • The key attribute contains the key value that was updated or removed in the storage.
  • The oldValue contains the previous value corresponding to the key before it was updated, and the newValue contains the value after the change. If the value was newly added, the oldValue will be null, and if the value has been removed, the newValue will be null.
  • The url attribute points to the origin where the storage event occurred.
  • Finally, the storageArea provides a convenient reference to the sessionStorage or localStorage where the value was changed. This gives the handler an easy way to query the storage for current values or make changes based on other storage changes.

Here is a simple event handler that will raise an alert dialog with the contents of any storage event fired on the page's origin.


// display the contents of a storage event
function displayStorageEvent(e) {
  var logged = "key:" + e.key + ", newValue:" + e.newValue + ", oldValue:" + 
               e.oldValue +", url:" + e.url + ", Storage Area: " + e.storageArea;

  alert(logged);
}

// add a storage event listener for this origin
window.addEventListener("storage", displayStorageEvent, true);


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video