Web Local Storage (localstorage, sessionstorage) description
For browsers, using Web Storage to store key values compared to storing cookies is more intuitive and more capacity, it contains two kinds: Localstorage and Sessionstorage
Sessionstorage (Temporary storage): maintains a storage area for each data source that exists during browser opening, including page reload
Localstorage (long-term storage): Same as Sessionstorage, but the data will persist after the browser is closed
Api
The usage of sessionstorage and localstorage is basically consistent, and the value of the reference type is converted to JSON
1. Save data to Local
const info = { name: ‘Lee‘, age: 20, id: ‘001‘ }; sessionStorage.setItem(‘key‘, JSON.stringify(info)); localStorage.setItem(‘key‘, JSON.stringify(info));
2. Getting data from local storage
var data1 = JSON.parse(sessionStorage.getItem(‘key‘)); var data2 = JSON.parse(localStorage.getItem(‘key‘));
3. Delete a saved data from the local store
sessionStorage.removeItem(‘key‘); localStorage.removeItem(‘key‘);
4. Delete all saved data
sessionStorage.clear(); localStorage.clear();
5. Monitor changes to local storage
Storage changes (add, update, delete) when the trigger, the same page changes will not trigger, will only listen to the same domain name other page changes Storage
window.addEventListener(‘storage‘, function (e) { console.log(‘key‘, e.key); console.log(‘oldValue‘, e.oldValue); console.log(‘newValue‘, e.newValue); console.log(‘url‘, e.url); })
Web Local Storage (localstorage, sessionstorage)