Lecture 7
Web Storage API
Web Storage API
API = application programming interface
Web Storage has two main mechanisms:
window.sessionStorage
window.localStorage
window.sessionStorage
maintains a separate storage area for each given origin that’s
available for the duration of the page session (as long as the browser
is open, including page reloads and restores).
window.localStorage
does the same thing, but persists even when the browser is closed and
reopened.
<form name="helloForm" method="get"
action="pageYouWantToDirectTo.html" onsubmit="validateForm()">
My Name: <input type="text" name="name">
<input type="submit" value="Submit">
</form>
function validateForm(){
var x = document.forms["helloForm"]["name"].value;
if (x == "") {
alert("I need to know your name so I can say Hello");
return false;
}
else{
alert("Hello there " + document.forms["helloForm"]["name"].value);
}
localStorage.setItem("username", x);
}
Setting and getting
localStorage.setItem("username", x);
// key - value pair
const username = localStorage.getItem('username');
console.log(username);