window.localStorage tutorial
EasyProgramming.net tutorial on window.localStorage
by DustyWhite
HTML
<!-- Easy JavaScript - localStorage and sessionStorage #50 -->
<p>
Welcome to the 50th Easy JavaScript tutorial, part of <a href="http://www.easyprogramming.net">EasyProgramming.net</a>. Did you know that you can store information in your browser to hold onto for the whole session? Even if you reload the page? Today, let's cover <code>window.localStorage</code>. We will utlize the JSON.stringify method in this tutorial.
</p>
<p>
HTML5 allows you to store information directly to your browser's memory, instead of cookies. localStorage is excellent for keeping data in a current session without using cookiesv (it's based on domain info). And unlike cookies, you can store up to 5MB of data. That's a lot of data! (One character is 8-bits or 1 byte, and 1 megabyte is 1 Million bytes!).
</p>
<p>
<code>window.localStorage</code> will keep the information based on the domain without an expiration. <code>window.sessionStorage</code> also exists, which will dete the data as soon as the browser tab is closed.
</p>
<p><b>Output:</b>
</p>
<div id="output"></div>
CSS
#output {
border:1px solid black;
padding: .5em;
}
JavaScript
// Initialize our person Object
var person = {
name: "Nazmus",
title: "Dev",
location: "Massachusetts",
website: "EasyProgramming.net",
}
var jsonPerson = JSON.stringify(person);
console.log(jsonPerson);
window.localStorage.setItem("person", jsonPerson);
var getItem = localStorage.getItem("person");
console.log(getItem);
var item = JSON.parse(getItem);
for (var p in item) {
document.getElementById("output").innerHTML += p + ': ' + item[p] + "<br />";
}
window.sessionStorage.setItem("website", "easyprogramming.net");