Local Storage Session Storage - Tuong-Nguyen/Angular-D3-Cometd GitHub Wiki
- It's a strings only key - value storage with a simplistic synchronous API (i.e. blocking requests)
- The localStorage object stores the data with no expiration date
- Designed for smaller amounts of data, storing simple session data.
Stores a user's name contains first name and last name
// Store
localStorage.setItem("firstname", "Will"); // or localStorage.firstname = "Will";
localStorage.setItem("lastname", "Smith"); // or localStorage.lastname = "Smith";
// Retrieve
document.getElementById("firstname").innerHTML = localStorage.getItem("firstname"); // or localStorage.firstname
document.getElementById("lastname").innerHTML = localStorage.getItem("lastname"); // or localStorage.lastname
- Delete a key
localStorage.remove('<key>');
- Clear all
localStorage.clear();
- The same as local storage, it's a strings only key - value storage, but it stores the data for only one session
- Designed for scenarios where the user is carrying out a single transaction or multiple transactions in different windows at the same time.
A user could be buying plane tickets in two different windows using the same site. If using cookies, this could potentially causing the user to buy two tickets for the same flight without really noticing.
- In html, a page could have a checkbox that user ticks to indicate that they want insurance
<label>
<input type="checkbox" onchange="sessionStorage.insurance = checked ? 'true' : ''">
I want insurance on this trip.
</label>
- In script, check whether user had checked the checkbox or not
if (sessionStorage.insurance) { ... }
The Session Storage Data would be deleted by the browsers immediately after the session gets terminated.
- How local storage is managed for different sites?
Local storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data.
- What are localStorage and sessionStorage assigned to?
It's global variables. They are
window.localStorage
andwindow.sessionStorage