Web Local Storage (localstorage, sessionstorage)

Source: Internet
Author: User
Tags sessionstorage

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

  1. Sessionstorage (Temporary storage): maintains a storage area for each data source that exists during browser opening, including page reload

  2. 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));
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
2. Getting data from local storage
    var data1 = JSON.parse(sessionStorage.getItem(‘key‘));    var data2 = JSON.parse(localStorage.getItem(‘key‘));
    • 1
    • 2
3. Delete a saved data from the local store
    sessionStorage.removeItem(‘key‘);    localStorage.removeItem(‘key‘);
    • 1
    • 2
4. Delete all saved data
    sessionStorage.clear();    localStorage.clear();
    • 1
    • 2
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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.