localStorage and sessionStorage:
localStorage.setItem(key, value) // – store key/value pair.
localStorage.getItem(key) // – get the value by key.
localStorage.removeItem(key) // – remove the key with its value.
localStorage.clear() // – delete everything.
localStorage.key(index) // – get the key on a given position.
localStorage.length // – the number of stored items.
sessionStorage.setItem(key, value) // – store key/value pair.
sessionStorage.getItem(key) // – get the value by key.
sessionStorage.removeItem(key) // – remove the key with its value.
sessionStorage.clear() // – delete everything.
sessionStorage.key(index) // – get the key on a given position.
sessionStorage.length // – the number of stored items.
localStorage and sessionStorage:
localStorage and sessionStorage:
// set key
localStorage.test = 2;
// get key
alert( localStorage.test ); // 2
// remove key
delete localStorage.test;
// Only Strings can be added
localStorage.user = JSON.stringify({name: "John"});
// accessing objects
let user = JSON.parse( localStorage.user );
alert( user.name ); // John
localStorage and sessionStorage:
// One way is to loop over them as over an array:
for(let i=0; i<localStorage.length; i++) {
let key = localStorage.key(i);
alert(`${key}: ${localStorage.getItem(key)}`);
}
// Another way is to use for key in localStorage loop,
// just as we do with regular objects.
// It iterates over keys, but also outputs
// few built-in fields that we don’t need:
// bad try
for(let key in localStorage) {
alert(key); // shows getItem,
// setItem and other built-in stuff
}
// …So we need either to filter fields
// from the prototype with hasOwnProperty check:
for(let key in localStorage) {
if (!localStorage.hasOwnProperty(key)) {
continue; // skip keys like "setItem", "getItem" etc
}
alert(`${key}: ${localStorage.getItem(key)}`);
}
// Or just get the “own” keys with Object.keys
// and then loop over them if needed:
let keys = Object.keys(localStorage);
for(let key of keys) {
alert(`${key}: ${localStorage.getItem(key)}`);
}
One of the most widespread use cases is authentication:
- Cookies are usually set by a web server using the response Set-Cookie HTTP header.
- Then, the browser automatically adds them to (almost) every request to the same domain using the Cookie HTTP header.
Steps overview:
- Upon sign-in, the server uses the Set-Cookie HTTP header in the API response to set a cookie with a unique “session identifier”.
- Next time the request is sent to the same domain (API call), the browser sends the cookie over the net using the Cookie HTTP header.
- So the server knows who made the request.
document.cookie // cookie1=value1; cookie2=value2;
document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
Few special cookies:
domain
domain=site.com
Few special cookies:
path
path=/mypath
Few special cookies:
expires, max-age
Few special cookies:
secure
secure
Few special cookies:
httpOnly
Third-party cookies