session and local storage code example
Example 1: session storage
sessionStorage.setItem('key', 'value');
let data = sessionStorage.getItem('key');
sessionStorage.removeItem('key');
sessionStorage.clear();
Example 2: store data in localstorage javascript
var testObject = { 'one': 1, 'two': 2, 'three': 3 };
localStorage.setItem('testObject', JSON.stringify(testObject));
var retrievedObject = localStorage.getItem('testObject');
console.log('retrievedObject: ', JSON.parse(retrievedObject));
Example 3: localStorage
var obj = {
firstName: "Bob",
lastName: "Jeff",
age: 13
}
localStorage.setItem("itemname", JSON.stringify(obj));
var item = JSON.parse(localStorage.getItem("itemname"));
Example 4: clear session storage on refresh
window.onunload = function () {
sessionStorage.removeItem('key');
}
Example 5: javascript save data to local storage
localStorage.lastname = "Smith";
document.getElementById("result").innerHTML = localStorage.lastname;
localStorage.removeItem("lastname");
Example 6: what is local storage and session storage in javascript