Javascript

Local Storage in JS

Local & Session storages in JS

           

  1. a) Local storage: Local storage are data , stored in small text file, on your browser without expiry date. Unlike COOKIE you can get data seperatelly. But read only
  • Store data => setItem ( “key” , “value” );
  • Get data => var x = getItem ( “key” );
  • Delete specific data => removeItem(“key”);

           

  1. b) Session storage: The sessionStorage object stores data for only one session (the data is deleted when the browser tab is closed.
  • Store data => setItem( “key”, “value” );
  • Get data => var x = getItem( “key” );
  • Remove specific data => removeItem( “key” );
  • Clear all session data => clear( );

 

Examples:1  ( Local Storage )

<div id=”result”></div>     // result -> Anderson

<script>

if (typeof(Storage) !== “undefined”) {       // Check browser support           localStorage.setItem(“lastname”, “Anderson”);       // Store data

document.getElementById(“result”).innerHTML =      // Get data localStorage.getItem(“lastname”);

} else {

document.getElementById(“result”).innerHTML = “Sorry, your browser does not support Local Storage…”; }

</script>

 

Examples:2  ( Session Storage )

<div id=”result”></div>                      // result -> Anderson

<script>

if (typeof(Storage) !== “undefined”) {       // Check browser support           sessionStorage.setItem(“lastname”, “Anderson”);       // Store data

document.getElementById(“result”).innerHTML =      // Get data sessionStorage.getItem(“lastname”);

} else {

document.getElementById(“result”).innerHTML = “Sorry, your browser does not support Session Storage…”; }

</script>

 

 

Leave a Reply