The storage objects enable you to set data that is “remembered” as the user visits all of the pages on your domain. There are two types of storage objects that we can establish, sessionStorage and localStorage. sessionStorage data is only available in the tab it was established in, and will expire when the tab is closed. localStorage data is more long term, it is available in all tabs and remains persistent even if the browser software is closed then re-opened. If you are familiar with PHP, sessionStorage is similar to SESSION data, and localStorage is similar to COOKIE data.
Using the example files below, navigate to somepage.html which will set the data, then click the “Go to other page” link to see how the data persists. Open a new tab to otherpage.html to see the difference in how it persists. Then close and re-open the browser software to otherpage.html to see which approach provides longer term data persistence.
<script> // Establish both types of storage data for a test otherpage.html
localStorage.setItem("firstname","Adam"); // persistent data
sessionStorage.setItem("lastname","Khoury"); // persistent session data
</script> <a href="otherpage.html">Go to other page</a>
<script> document.write(localStorage.firstname+" "+sessionStorage.lastname); </script>
Notice how sessionStorage data is not available when you open otherpage.html in a new tab, or if the browser is closed. And notice how localStorage data remains persistent even in new browsing tabs and when browser is closed/opened.
length – returns the number of data items in a storage object’s list.
var sess_len = sessionStorage.length; var local_len = localStorage.length;
clear() – clears the data in a storage object’s list.
key() – returns the name of the key at the given index in a storage object’s item list.
var key0 = localStorage.key(0); var key1 = localStorage.key(1); // etc...
getItem() – returns the value associated with a given key name.
var fname = localStorage.getItem("firstname"); // or
var fname = localStorage.getItem(localStorage.key(0));
setItem() – set(or use to update) items in a storage object’s item list.
removeItem() – removes an item from a storage object’s list by the given key name.
Storage Disk Space
An arbitrary space limit suggested for stored data in various browser software is 5 megabytes. The browser software may prompt the user when the limit is reached and allow the user to grant more storage space to a specific site. Web storage and cookie data in general is tied to the browser software the user accessed the pages with, and not shared with their other browser software they may have installed on their machine.