What is the difference between localStorage, sessionStorage, session and cookies?

后端 未结 8 1567
抹茶落季
抹茶落季 2020-11-22 03:07

What are the technical pros and cons of localStorage, sessionStorage, session and cookies, and when would I use one over the other?

8条回答
  •  攒了一身酷
    2020-11-22 03:44

    These are properties of 'window' object in JavaScript, just like document is one of a property of window object which holds DOM objects.

    Session Storage property maintains a separate storage area for each given origin that's available for the duration of the page session i.e as long as the browser is open, including page reloads and restores.

    Local Storage does the same thing, but persists even when the browser is closed and reopened.

    You can set and retrieve stored data as follows:

    sessionStorage.setItem('key', 'value');
    
    var data = sessionStorage.getItem('key');
    

    Similarly for localStorage.

提交回复
热议问题