A quick guide on how to use localStorage and sessionStorage APIs
localStorage
localStorage is a web storage API available in modern web browsers that allows developers to store data on the client side without an expiration date. It provides a key-value store for storing data in the user's web browser, and data stored in localStorage is accessible across multiple pages or tabs within the same browser session. localStorage has a limit of around 5-10 MB depending on the browser and is commonly used for storing small amounts of data such as user preferences or temporary data needed for a single user.
Storing data:
To store data in local storage, use the localStorage.setItem() method.
For example:
localStorage.setItem('key', 'value');
This will store the value "value" under the key "key" in local storage.
Retrieving data:
To retrieve data from local storage, use the localStorage.getItem() method.
For example:
const value = localStorage.getItem('key');
This will retrieve the value stored under the key "key" and assign it to the variable "value".
Updating data:
To update data in local storage, simply use the localStorage.setItem() method again with the same key. For example:
localStorage.setItem('key', 'new value');
This will update the value stored under the key "key" to "new value".
Deleting data:
To remove data from local storage, use the localStorage.removeItem() method.
For example:
localStorage.removeItem('key');
This will remove the item stored under the key "key" from local storage.
Clearing all data:
To remove all data from local storage, use the localStorage.clear() method.
For example:
localStorage.clear();
This will remove all items stored in local storage.
sessionStorage
sessionStorage is a web storage API available in modern web browsers that allows developers to store data on the client side for only one session (i.e. until the user closes the browser tab or window). It provides a key-value store for storing data in the user's web browser, and data stored in sessionStorage is accessible across multiple pages or tabs within the same browser session. sessionStorage has a limit of around 5-10 MB depending on the browser and is commonly used for storing small amounts of data that need to be cleared when the user closes the browser tab or window, such as temporary data or user session information.
Storing data:
To store data in sessionStorage, use the sessionStorage.setItem() method.
For example:
sessionStorage.setItem('key', 'value');
This will store the value "value" under the key "key" in sessionStorage.
Retrieving data:
To retrieve data from sessionStorage, use the sessionStorage.getItem() method.
For example:
const value = sessionStorage.getItem('key');
This will retrieve the value stored under the key "key" and assign it to the variable "value".
Updating data:
To update data in sessionStorage, simply use the sessionStorage.setItem() method again with the same key. For example:
sessionStorage.setItem('key', 'new value');
This will update the value stored under the key "key" to "new value".
Deleting data:
To remove data from sessionStorage, use the sessionStorage.removeItem() method.
For example:
sessionStorage.removeItem('key');
This will remove the item stored under the key "key" from sessionStorage.
Clearing all data:
To remove all data from sessionStorage, use the sessionStorage.clear() method.
For example:
sessionStorage.clear();
This will remove all items stored in sessionStorage.
Exporting all localStorage data
// Get all keys in local storage const keys = Object.keys(localStorage);
// Create an object to hold the data const data = {};
// Loop through each key and add the corresponding value to the data object keys.forEach((key) => { data[key] = localStorage.getItem(key); });
// Convert the data object to a JSON string const jsonString = JSON.stringify(data);
// Create a link to download the JSON file const link = document.createElement('a'); link.setAttribute('href', `data:text/json;charset=utf-8,${encodeURIComponent(jsonString)}`); link.setAttribute('download', 'local-storage-data.json');
// Click the link to download the JSON file document.body.appendChild(link); link.click(); document.body.removeChild(link);
Importing localStorage data
This sample code requires <body> element on an html page.
// Create an input element to select the file const input = document.createElement('input'); input.type = 'file'; input.accept = '.json'; input.style.display = 'none';
// Add an event listener to the input element to handle the file selection input.addEventListener('change', (event) => { const file = event.target.files[0]; if (file) { // Read the contents of the selected file as a JSON object const reader = new FileReader(); reader.readAsText(file, 'UTF-8'); reader.onload = (event) => { const data = JSON.parse(event.target.result); // Loop through each key-value pair in the data object and store it in local storage for (const [key, value] of Object.entries(data)) { localStorage.setItem(key, value); } console.log('Local storage data imported successfully.'); }; reader.onerror = (event) => { console.error('Error importing local storage data:', event.target.error); }; } });
// Trigger the built-in file selection window when a button is clicked const button = document.createElement('button'); button.textContent = 'Import Local Storage Data'; button.addEventListener('click', () => { input.click(); });
// Add the button to the webpage document.body.appendChild(button);
When I look back on my past and think how much time I wasted on nothing, how much time has been lost in futilities, errors, laziness, incapacity to live; how little I appreciated it, how many times I sinned against my heart and soul — then my heart bleeds. Life is a gift, life is happiness, every minute can be an eternity of happiness. — Fyodor Dostoevsky, Letter to His Brother