Local Storage

With local storage, web applications can store data locally within the user's browser.

Before HTML5, application data had to be stored in cookies, included in every server request. (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. )

Local storage is more secure, and large amounts of data can be stored locally, without affecting website performance.

Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.

Local storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data.

HTML local storage provides two objects for storing data on the client:

  • window.localStorage - stores data with no expiration date
  • window.sessionStorage - stores data for one session (data is lost when the browser tab is closed)

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.

// Using property 
// You can set properties on the sessionStorage 
// and localStorage object just like with a normal
// JavaScript object.

sessionStorage.myProperty = "Hello World";

localStorage.myProperty   = "Hello World";
// Use the square bracket for the property with invalid 
// characture for property name

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

localStorage["Invalid JS Property Name"] = "Hello World";
// Using set/get items 

// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');

console.log('retrievedObject: ', JSON.parse(retrievedObject));
_getCartJson = function () {
   try {
         if (localStorage 
         && localStorage[cartLocalStorageName] 
         && localStorage[cartLocalStorageName].length > 0)      {
         return JSON.parse(localStorage[cartLocalStorageName]);
           }
        } catch (e) { }
            return [];
   },


_setCartJson = function () {
try {
       if (cartData.data().length == 0) {

            localStorage.removeItem(cartLocalStorageName);
        } 
        else {
            localStorage[cartLocalStorageName] = 
            JSON.stringify(cartData.data());
         }
       } catch (e) {
        alert("There was a problem saving your shopping
         cart to the browser local storage.");
      }


var testObject = { 'one': 1, 'two': 2, 'three': 3 };

Libraries

results matching ""

    No results matching ""