β¦ π 3 min, π 6 min
localStorage from JS simply do:localStorage.setItem('myCat', 'Tom');
or any other object (list, int, dict). Then to retrieve it:let cat = localStorage.getItem('myCat');
and to remove it:localStorage.removeItem('myCat');
or to clear all items in the local storage that belong to the current domain, we are on:localStorage.clear();
There's another storage object sessionStorage. Same interface as local storage though session storage get's purged once the user leaves the site. Friendly note: I would avoid storing any sensitive data (personal or security) into the local storage.localStorage.localStorage is blocked and will throw a quota exceeded error. So we might want to check if the browser is in incognito mode to be on the safe side.try catch block and then analyze what happened.Function get_local_storage_status() will give us the status of localStorage :function get_local_storage_status() {
let test = "test";
try {
// try setting an item
localStorage.setItem("test", test);
localStorage.removeItem("test");
}
catch(e)
{
// browser specific checks if local storage was exceeded
if (e.name === "QUATA_EXCEEDED_ERR" // Chrome
|| e.name === "NS_ERROR_DOM_QUATA_REACHED" //Firefox/Safari
) {
// local storage is full
return "full";
} else {
try{
if(localStorage.remainingSpace === 0) {// IE
// local storage is full
return "full";
}
}catch (e) {
// localStorage.remainingSpace doesn't exist
}
// local storage might not be available
return "unavailable";
}
}
return "available";
}
We can then run the function with:get_local_storage_status();
Or display the status in the console:console.log(get_local_storage_status())
A convenient test to see if our script works is to disable local storage, for example in Firefox by:about:config in your address bar and hit enter. You'll see browser settings.dom.storage.enabled and change status to false. Double mouse click on the setting should do the change.console for the status. If you managed to set up the Firefox settings correctly the console.log(get_local_storage_status()) should give you "unavailable" status.HTML5 and localStorage at all. In that case well ...
Get notified & read regularly π