CIS 119 - Web storage (DOM storage)
Objectives
- discuss advantages of web storage over use of cookies
- discuss and use localStorage
- discuss and use sessionStorage
Overview
- web storage provides a lot more storage capacity than cookies (5MB-10MB vs. 4K)
- web storage is completely client-side - no information is automatically sent via headers to the server
- web storage is divided into sessionStorage and localStorage
- sessionStorage is limited to a particular page in a particular window while the browser is running
- localStorage is limited to a particular domain and persists even after a browser is shut down
Using sessionStorage and localStorage
- values are saved as key:value pairs
- saving the value 42 with the key num: sessionStorage.setItem('num', '42');
- saving the value 42 with the key num: localStorage.setItem('num', '42');
- retrieving the value for key num: sessionStorage.getItem('num');
- retrieving the value for key num: localStorage.getItem('num');
- objects can be stored using JSON to turn the object into a string: JSON.stringify({'width':5,'height':10})
- retrieved JSON strings can be converted back to objects using JSON.parse(JSON_String)
- sessionStorage and localStorage have a length attribute to tell you how many key:value pairs are stored
- retrieving a specific key by index number: sessionStorage.key(2)
- retrieving a specific key by index number: localStorage.key(2)
- removing the key:value pair where key is num: sessionStorage.removeItem('num')
- removing the key:value pair where key is num: localStorage.removeItem('num')
- clearing all key:value pairs: sessionStorage.clear()
- clearing all key:value pairs: localStorage.clear()
Storage demonstration code
See the live storage demonstration.
This example allows you to store and display a name value in either local or session storage.
<!DOCTYPE html>
<html lang="en">
<head>
<title>WebStorage</title>
<meta charset="utf-8">
<script>
function saveSession() {
if (!sessionStorage) {
alert("Your browser does not support session storage");
} else {
var elem = document.getElementById('name');
sessionStorage.setItem('name', elem.value);
document.getElementById('result').innerHTML = elem.value;
}
return false;
}
function saveLocal() {
if (!localStorage) {
alert("Your browser does not support local storage");
} else {
var elem = document.getElementById('name');
localStorage.setItem('name', elem.value);
document.getElementById('result').innerHTML = elem.value;
}
return false;
}
function clearStorage() {
if (localStorage) localStorage.clear();
if (sessionStorage) sessionStorage.clear();
document.getElementById('result').innerHTML = "";
return false;
}
window.onload = function() {
var found = false;
var value = null;
if (sessionStorage) value = sessionStorage.getItem('name');
if (value == null && localStorage) value = localStorage.getItem('name');
document.getElementById('result').innerHTML = value;
};
</script>
</head>
<body>
<div>The stored value is <span id="result"></span></div>
<form>
<p><label for="name">Name</label>
<input type="text" id="name"></p>
<p><input type="submit" value="Session storage save" onclick="return saveSession();"></p>
<p><input type="submit" value="Local storage save" onclick="return saveLocal();"></p>
<p><input type="submit" value="Clear storage" onclick="return clearStorage();"></p>
</form>
</body>
</html>
More storage demonstration code
See the additional storage demonstration.
This example allows you to store and display multiple key/value pairs of your choosing.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Web Storage Demo 2</title>
<meta charset="utf-8">
<style>
#results {
font-family: monospace;
whitespace: pre;
}
label {
display: inline-block;
width: 4em;
}
</style>
<script>
function $(id) {
return document.getElementById(id);
}
function clearTextBoxes() {
$('value').value = "";
$('key').value = "";
}
function saveSession() {
if (!sessionStorage) {
alert("Your browser does not support session web storage");
} else {
var key = $('key').value;
var value = $('value').value;
if (key && value) sessionStorage.setItem(key, value);
else alert("Either the key or value (or both) were missing.");
window.location.reload();
}
clearTextBoxes();
return false;
}
function saveLocal() {
if (!localStorage) {
alert("Your browser does not support local web storage");
} else {
var key = $('key').value;
var value = $('value').value;
if (key && value) localStorage.setItem(key, value);
else alert("Either the key or value (or both) were missing.");
window.location.reload();
}
clearTextBoxes();
return false;
}
function clearStorage() {
if (localStorage) localStorage.clear();
if (sessionStorage) sessionStorage.clear();
window.location.reload();
return false;
}
window.onload = function() {
clearTextBoxes();
$('btnSaveLocal').onclick = saveLocal;
$('btnSaveSession').onclick = saveSession;
$('btnClear').onclick = clearStorage;
var msg = "";
var i = 0;
if (sessionStorage) {
var ssLength = sessionStorage.length;
if (ssLength > 0) {
msg += '<h3>Session storage</h3>';
msg += '<ol type="1">';
for (i=0; i<ssLength; i++) {
var ssKey = sessionStorage.key(i);
msg += '<li>' + ssKey + ' = ' + sessionStorage.getItem(ssKey) + '</li>';
}
msg += '</ol>';
}
}
if (localStorage) {
var lsLength = localStorage.length;
if (lsLength > 0) {
msg += '<h3>Local storage</h3>';
msg += '<ol type="1">';
for (i=0; i<lsLength; i++) {
var lsKey = localStorage.key(i);
msg += '<li>' + lsKey + ' = ' + localStorage.getItem(lsKey) + '</li>';
}
msg += '</ol>';
}
}
if (!localStorage && !sessionStorage) $('results').innerHTML = '<h3>Web storage not available.</h3>';
else if (msg == "") $('results').innerHTML = '<h3>No data found in web storage.</h3>';
else $('results').innerHTML = msg;
};
</script>
</head>
<body>
<div id="results"></div>
<form>
<p><label for="key">Key: </label><input type="text" id="key"></p>
<p><label for="value">Value: </label><input type="text" id="value"></p>
<p><button type="button" id="btnSaveSession">Session storage save</button></p>
<p><button type="button" id="btnSaveLocal">Local storage save</button></p>
<p><button type="button" id="btnClear">Clear storage</button></p>
</form>
</body>
</html>