Web Storage

Web Storage comes in two flavors—localStorage and sessionStorage—and are very similar to cookies in that they allow you to use JavaScript to set name/value pairs that you can retrieve across multiple page reloads.

Unlike cookies, however, Web Storage data is not sent across the wire with the browser request—it lives entirely in the client. Therefore, it's feasible to store much more data than you would want to with cookies.

At the time of this writing, browser size limits for Web Storage are still in flux. However, my most recent tests indicate that the limit is right around 2.5 MB.

Functionally, localStorage and sessionStorage are the same. They differ only in terms of persistence and scope:


Data is saved even after the window is closed and is available to all windows (or tabs) that are loaded from the same source (must be the same domain name, protocol, and port). This is useful for things like application preferences.


Data is stored with the window object. Other windows/tabs are not aware of the values, and the data is discarded when the window/tab is closed. Useful for window-specific state like active tab highlight or the sort order of a table.

In any of the following examples, you can substitute sessionStorage anywhere you see localStorage, but remember that sessionStorage goes away when you close the window or tab.

Setting a value is as simple as the following: localStorage.setItem('age', 40);

Accessing a stored value is equally simple: var age = localStorage.getltem('age');

You can delete a specific key/value pair from storage like so: localStorage.removeltem('age');

Or, you can delete all key/value pairs like so: localStorage.clear();

Assuming your keys are valid JavaScript tokens (e.g., no spaces, no punctuation other than underscores) you can use this alternate syntax:

localStorage.age = 40 // Set the value of age var age = localStorage.age; // Get the value of age delete localStorage.age; // Remove age from storage

The localStorage and sessionStorage keys are stored separately. If you use the same key name for each, they will not conflict with each other.

0 0

Post a comment