HTML5 Local Storage

Jakob Jenkov
Last update: 2016-02-08

HTML5 local storage makes it possible to store values in the browser which can survive the browser session. In that way HTML5 local storage is similar to cookies, but has some differences which I will discuss a bit later in this tutorial. HTML5 Local storage also makes it possible to send events between browser windows. A very useful feature. This HTML5 local storage tutorial will explain how to use HTML5 local storage to achieve this.

Local storage is a new specification in HTML. It is not actually part of the HTML5 specification, but it is born around the same time, and is often referred to as being part of the new HTML platform (which is HTML5). Therefore I include the local storage tutorial in my HTML5 tutorial trail.

HTML5 Local Storage vs Cookies

As mentioned earlier, HTML5 local storage is similar to cookies in that both mechanisms can be used to store data in the browser between HTTP requests. But there is a difference between HTML5 local storage and cookies.

Cookies are small pieces of data which a server can store in the browser. The cookie is sent by the browser along with all future HTTP requests to the server that set the cookie. Cookies cannot be bigger than 4KB in total.

HTML5 local storage is set via JavaScript executed in the browser. HTML5 local storage properties are never sent to any server - unless you explicitly copy them out of the local storage and appends them to an AJAX request. HTML5 local storage can store somewhere between 2MB and 10MB data in the browser (per origin - domain name). Exactly how much data is allowed depends on the browser. A limit of 5MB to 10MB is most common.

HTML5 Local Storage Security

The properties set in the HTML5 local storage can only be read by pages from the same domain as the page that set the properties. Thus, if a page from jenkov.com sets some local storage properties, only pages from jenkov.com can read these properties. The URL does not have to be the same, but the domain name does.

HTML5 Local Storage Basics

HTML5 local storage offers a simple key - value store, like a hash table or dictionary object. Actually, the local storage object looks very similar to a regular JavaScript object, with the exception that it is stored in the browser, even if the page is unloaded.

Local Storage vs. Session Storage

Local storage comes in two versions:

  1. Session Storage
  2. Local Storage

Session storage is available inside the same browser window for as long as the window is open. When the browser window is closed, the session storage associated with that window is deleted. Multiple windows from the same origin (URL) cannot see each others session storage. Popup windows opened from the same window can see session storage, and so can iframes inside the same window.

Local storage is available in the browser to all windows with the same origin (domain). Data stored in the local storage is also available after the window has been closed. The next time a window is opened and loads the page from the same origin, the page can access the stored values there again.

sessionStorage + localStorage

The session storage and local storage are accessed via these two globally available JavaScript objects:

  • sessionStorage
  • localStorage

The sessionStorage object and localStorage object are accessed in the same way. It is only the life span and visibility of the data stored that is different.

Setting Properties

You can set properties on the sessionStorage and localStorage object just like with a normal JavaScript object. Here is an example:

sessionStorage.myProperty = "Hello World";

localStorage.myProperty   = "Hello World";

The first line of this code example sets the session storage property myProperty to the value Hello World. The second line sets the local storage property myProperty to the value Hello World.

If your property names contain characters which are not allowed in JavaScript variable names, you will need to use the square bracket access mode to set a property, like this:

sessionStorage["Invalid JS Property Name"] = "Hello World";
    
localStorage["Invalid JS Property Name"] = "Hello World";

Or, you can use the setItem() function, like this:

sessionStorage.setItem("Invalid JS Property Name", "Hello World");

Getting Properties

You can get properties from the sessionStorage and localStorage objects like this:

var myProp = sessionStorage.myProperty;

var myProp = localStorage.myProperty;

If the property name is not a valid JavaScript variable name, you will need to use the square bracket access method, like this:

var myProp = sessionStorage["myProperty"];

var myProp = localStorage["myProperty"];

Or you can use the getItem() function, like this:

var myProp = sessionStorage.getItem("myProperty");

var myProp = localStorage.getItem("myProperty");

Deleting Properties

You delete a session or local storage property like this:

delete sessionStorage.myProperty;

delete localStorage.myProperty;

Or you can use the removeItem() function, like this:

sessionStorage.removeItem ("myProperty");

Clearing the Local Storage

If you want to delete all properties stored in the sessionStorage or localStorage objects, you can use the clear() function. Here is a clear() function call example:

sessionStorage.clear();

localStorage.clear();

Reading Number of Properties Stored

You can read the number of properties stored in the sessionStorage or localStorage objects using the length property, like this:

var length = sessionStorage.length;

var length = localStorage.length;

Iterating Keys in the Local Storage

You can iterate the keys (property names) of the key - value pairs stored in the sessionStorage or localStorage, like this:

for(var i=0; i < sessionStorage.length; i++){

    var propertyName = sessionStorage.key(i);

    console.log(  i + " : " + propertyName + " = " +
            sessionStorage.getItem(propertyName));
}

The sessionStorage.length property returns the number of properties stored in the sessionStorage object.

The function key() returns the property name (or key name) of the property with the index passed as parameter to the function.

You can iterate the keys of the localStorage in the same way. Just exchange the sessionStorage object with the localStorage object in the example above.

Local Storage Events

When you modify the sessionStorage or localStorage the browser fires storage events. A storage event is fired when you insert, update or delete a sessionStorage or localStorage property.

The storage event is only emitted in other browser windows than the window that performed the modification. For sessionStorage this means that events are only visible in pop up windows and iframes, since each browser window has its own sessionStorage object.

For the localStorage object which is shared across browser windows, events are visible to all other windows open with the same origin (protocol + domain name), including pop up windows and iframes.

Attaching a Storage Event Listener

Attaching an event listener to a local storage object is done like this:

function onStorageEvent(storageEvent){

    alert("storage event");
}

window.addEventListener('storage', onStorageEvent, false);

The function onStorageEvent() is the event handler function.

The addEventListener() function call attaches the event handler function to storage events.

The storageEvent event object passed to the event handler function looks like this:

StorageEvent {
    key;          // name of the property set, changed etc.
    oldValue;     // old value of property before change
    newValue;     // new value of property after change
    url;          // url of page that made the change
    storageArea;  // localStorage or sessionStorage,
                  // depending on where the change happened.
}

You can access this storage event object from inside the event handler function.

Jakob Jenkov

Featured Videos

Java ConcurrentMap + ConcurrentHashMap

Java Generics

Java ForkJoinPool

P2P Networks Introduction

















Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next