Softnami
Author: Hussain Mir Ali

I am interested in web and mobile technologies.

If you any questions or feedback then message me at devtips@softnami.com.

Announcements
Ads

Call predictor: AI based call prediction

Download

2020

Feb
Jan

2019

Dec
Nov
Jul
May
Mar
Jan

2018

Nov
Sep
Jul
Jun
Apr
Feb
Jan

2017

Dec
Oct
Sep
Aug
Jul
Jun
May
Apr
Mar
Jan

2016

Dec
Oct
Sep
Aug
Jul

Data Persistence in Browser with JavaScript Part-2

WebStorage API provides a way to store information using 'key/value' pair in the browser.  The API consists of 'localStorage' and 'sessionStorage' objects which extend the 'Storage' interface and serve different purposes. The WebStorage API maintains memory for a specific origin for both 'localStorage' and 'sessionStorage'. Each of these interfaces are controlled separately but there is difference between persistence of data in certain use cases.

sessionStorage:

The 'sessisonStorage' is intended to be used for maintaining session information like user settings. The memory is maintained specific to a particular origin. For instance origin of 'www.youtube.com' will have different information compared to 'www.facebook.com' . Also 'sessionStorage' maintains information for different tabs separately even for the same origin. If the tab is closed or the browser is closed the 'sessionStorage' will loose data specific to that origin and tab. 

Sample usage:
if (typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage
sessionStorage.setItem('test1', 100);
sessionStorage.setItem('test2', 600);

console.log(sessionStorage.getItem('test1'));//100
sessionStorage.removeItem('test1');
console.log(sessionStorage.getItem('test1'));//null

console.log(sessionStorage.key(0));//test2
sessionStorage.clear();
console.log(sessionStorage.getItem('test2'));//null
} else {
// No Web Storage support
}

localStorage:

Unlike 'sessionStorage' the 'localStorage' can be shared across tabs for the same origin. Also data persists even after closing tabs or the browser. So data needs to be explicitly removed for a specific origin. . 

Sample usage:
if (typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage
localStorage.setItem('username', 'fred76283');
localStorage.setItem('likes', 'puzzle games');

console.log(localStorage.getItem('username'));//fred76283
localStorage.removeItem('username');
console.log(localStorage.getItem('username'));//null

console.log(localStorage.key(0));//likes
localStorage.clear();
console.log(localStorage.getItem('likes'));//null
} else {
// No Web Storage support
}
localStorage and sessionStorage methods:

key(a):  This method returns the key for specific index 'a'.

getItem(f):  This method returns the value for a specific key 'f'.

setItem(f,n):   This method sets the value 'n' for a specific key 'f'.

removeItem(f):  This method removes the key-value pair associated with a key 'f'.

clear(): This method removes all key-value pairs from the specific storage(local/session).