Lecture 7

Web Storage API

Web Storage API

API = application programming interface

Web Storage API

Refer to the docs:

https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API

One of 5 mechanisms:

https://developer.mozilla.org/en-US/docs/Web/API/Storage_API/Storage_quotas_and_eviction_criteria#what_technologies_store_data_in_the_browser

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.

forms

Data is easily collected from <form>

<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);