Html 5 Web Storage

Introduction

The Web Storage API defines a standard for how we can save simple data locally on a user’s computer or device. Before the emergence of the Web Storage standard, web developers often stored user information in cookies, or by using plugins. With Web Storage, we now have a standardized definition for how to store up to 5MB of simple data created by our websites or web applications.

Browser Support for Web Storage:

Web Storage is supported in these browsers:

  • ■ Safari 4+
  • ■ Chrome 5+
  • ■ Firefox 3.6+
  • ■ Internet Explorer 8+
  • ■ Opera 10.5+
  • ■ iOS (Mobile)

HTML5 introduced two new APIs for in-browser persistent data storage: sessionStorage and localStorage. To test if a browser supports either of the Storage APIs, use the following feature-detect:

var storage_support = window.sessionStorage || window.localStorage;
Local Storage versus Cookies

Local storage play a similar role to HTTP cookies, but there are a few key differences.

Cookies are intended to be read on the server side, whereas local storage is only available on the client side. If you need your server-side code to react differently based on some saved values, cookies are the way to go. Yet, Cookies are sent along with each HTTP request to your server and this can result in significant overhead in terms of bandwidth.

Local storage, just sits on the user’s hard drive waiting to be read, so it costs nothing to use.

In addition, we have significantly more size to store things using local storage. With cookies, we could only store 4KB of information in total.With local storage, the maximum is 5MB.
Web Storage is Browser-specific
Web storage stores data specific to browser. If the user visits a site in Safari, any data will be stored to Safari’sWeb Storage store. If the user then revisits the same site in Chrome, the data that was saved via Safari will be unavailable. Each browser’s storage is separate and independent. --

Browser Support Test

HTML5 introduced two new APIs for in-browser persistent data storage: sessionStorage and localStorage.

To test if a browser supports either of the Storage APIs, use the following feature-detect:

snippet
var storage_support = window.sessionStorage || window.localStorage;
--

Web Storage Types

HTML5 introduced two new APIs for in-browser persistent data storage: sessionStorage and localStorage.

The difference between the two is basically how long the browser persists the data.

Session Storage

Session Storage stores data only for the lifetime of the browser instance/session.

Session storage lets us keep track of data specific to one window or tab. Even if the user is visiting the same site in two windows, each window will have its own individual session storage object and thus have separate, distinct data.

Session storage is not persistent—it only lasts for the duration of a user’s session on a specific site (in other words, for the time that a browser window or tab is open and viewing that site).

Local Storage

Local Storage stores data persistently "forever."

Unlike session storage, local storage allows us to save persistent data to the user's computer, via the browser. When a user revisits a site at a later date, any data saved to local storage can be retrieved.

Note
Data stored in these containers must be strings, so if you need to store complex data objects, one good option is to serialize the object into JSON, using JSON.stringify().
---

Manipulating Storage Data

Data saved in Web Storage is stored as key/value pairs.

A few examples of simple key/value pairs:

  • ■ key: name, value: Fernando
  • ■ key: painter, value: David
  • ■ key: email, value: info@rookienerd.com
Setting the data
(I) sessionStorage

To store some data for only the current browser instance (goes away when the user closes the browser), use sessionStorage

snippet
var user_id = "A1B2C3D4";
var user_data = {
    name: "Tom Hanks",
    occupation: "Actor",
    favorite_color: "Blue"
        // ...
};
sessionStorage.setItem(user_id, JSON.stringify(user_data));
(II) localStorage

To store some data for a longer period of time, use localStorage

snippet
var user_id = "A1B2C3D4";
var user_prefs = {
    keep_me_logged_in: true,
    start_page: "daily news"
        // ...
};
localStorage.setItem(user_id, JSON.stringify(user_prefs));
Shortcut Way:-

Instead of localStorage.setItem(key, value), we can say localStorage[key]= value: localStorage["size"] = 6;

localStorage.setItem(key, value)

[or]

localStorage[key]= value
Getting the data

To pull data from the storage container:

snippet
var user_id = "A1B2C3D4";
var user_data = { /* defaults */ };
var user_prefs = { /* defaults */ };
if (sessionStorage.getItem(user_id)) {
    user_data = JSON.parse(sessionStorage.getItem(user_id));
}
if (localStorage.getItem(user_id)) {
    user_prefs = JSON.parse(localStorage.getItem(user_id));
}

These Storage APIs allow you to very simply set and retrieve key/value data, where the value is a string, but can represent anything you want, including the string serialization of a complex data object.

Shortcut Way:-

Instead of localStorage.getItem(key), we can simply say localStorage[key].

var size = localStorage["size"];
Removing Items and Clearing Data
MethodDescription
removeItem(key)To remove a specific item from Web Storage, we can use the removeItem method. We pass it the key we want to remove, and it will remove both the key and its value.
clear() To remove all data stored by our site on a user's computer, we can use the clear method. This will delete all keys and all values stored for our domain.
--

Web Storage API Methods

The APIs for both sessionStorage and localStorage are identical:

MethodDescription
getItem(key)Returns an item of data from the storage container, referenced by its key
setItem(key, item)Adds an item of data to the storage container, referenced by its key
key(index)Returns the key for an item of data at the numerical index specified
removeItem(key)Removes an item from the storage container, referenced by its key
clear()Clears out all data in the current storage container
lengthIdentifies how many items of data are in the storage container
--

Web Storage Limits

Internet Explorer "allows web applications to store nearly 10MB of user data. Chrome, Safari, Firefox, and Opera all allow for up to 5MB of user data, which is the amount suggested in the W3C spec.

Test Storage Exceed

A better approach to test to see if the quota is exceeded before saving important data. The way you test for this is by catching the QUOTA_EXCEEDED_ERR exception.

snippet
try {
    sessionStorage["name"] = "Tabatha";
} catch (exception) {
    if (exception == QUOTA_EXCEEDED_ERR) {
        // we should tell the user their quota has been exceeded.
    }
}
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +