JavaScript: Web Storage Tutorial: localStorage, sessionStorage

,
Want to master JavaScript in a week? Buy Xah JavaScript Tutorial.

Web Storage is a mechanism for JavaScript to store data in the client's browser. It's like cookies, but more clean and powerful. 〔➤ JavaScript: Checking, Getting, Setting, Cookies

Web Storage is very simple. It's just a pre-defined special property of browser's window object.

There are 2 storage properties:

// simple example of storing data
window.localStorage["myLetters"] = "abc";
console.log(window.localStorage["myLetters"]); // prints "abc"

JavaScript localStorage test (play in your browser console)

These pre-defined properties will save the data in browser. When user visits the site later, the localStorage value will still be available. (if user didn't delete the browser's cache.)

Turn on Browser Cookies

If browser's cookies is turned off, web storage won't work. If you try to set storage when cookies is off, you get this error in Firefox:

SecurityError: The operation is insecure.

String Data Only

As of , only string can be saved. (that is, the value of any property of localStorage is always string data type) Any other type, such as number, will be converted to string. Same thing for sessionStorage.

You can try by typing the following in your browser's console:

window.localStorage.x = 123;
console.log(typeof window.localStorage.x);

Getter & Setter Methods

localStorage has the following methods and properties:

localStorage methods & properties
syntaxmeaning
localStorage.getItem(key)return the key's value.
localStorage.setItem(key, value)set the key to value.
localStorage.removeItem(key)remove the item.
localStorage.clear()remove all data.
localStorage.key(i)return the name (string) of the ith item. (Object's property are not ordered. Use this in a “for loop” to access all items.)
localStorage.lengthnumber of items.

sessionStorage has the same methods and properties.

It's better if you use these methods to access/set properties.

Example:

// do this
window.localStorage.setItem("xx","abc");    // set value
var yy = window.localStorage.getItem("xx"); // get value

// don't do this
window.localStorage["xx"] = "abc";  // set value
var yy = window.localStorage["xx"]; // get value

Using the normal syntax of accessing property with Dot Notation or Bracket Notation (e.g. localStorage.o={"x":1}) creates a semantic inconsistency, because the localStorage is a special property, not a normal JavaScript property. Here's a example:

// example of inconsistency if browser supports storing objects
localStorage.o = {x:1}; // Store a object
localStorage.o.x = 2; // try to set the property of the stored object
localStorage.o.x // returns 1. x is unchanged
// this example is from David Flanagan's JavaScript Definitive Guide
// Note: as of 2014-03-01, browsers only support storing string.

View Storage Data from Browser's Developer Tool

Some browsers have dev tools to let you view storage data.

Google Chrome browser dev tool local storage screenshot 2014-03-01
Google Chrome browser dev tool, showing the local storage data.

Web Storage, Same Origin Policy

Data stored in localStoragesessionStorage can only be accessed from a page that has the “same origin” as the current page, by the “same origin policy”.

A “origin” is the combination of {protocol used, host name, port number}.

For example, none of the following URLs have the same origin.

This also applies to embedded iframes in a page. (that is, if the embedded iframe is loaded from a URL that's not the same origin, then, the iframe's JavaScript cannot access the storage data.)

localStorage vs sessionStorage

What's the difference between localStorage and sessionStorage?

localStorage is “permanent”. The data remains unless the user deletes it thru the browser's “clear cache” feature.

sessionStorage is per session only. The data will be gone when user closes the tab, window, or quit browser.

Reference

blog comments powered by Disqus