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

后端 未结 8 1547
抹茶落季
抹茶落季 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:47

    LocalStorage:

    • Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity. Available size is 5MB which considerably more space to work with than a typical 4KB cookie.

    • The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - reducing the amount of traffic between client and server.

    • The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.

    • It works on same-origin policy. So, data stored will only be available on the same origin.

    Cookies:

    • We can set the expiration time for each cookie

    • The 4K limit is for the entire cookie, including name, value, expiry date etc. To support most browsers, keep the name under 4000 bytes, and the overall cookie size under 4093 bytes.

    • The data is sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - increasing the amount of traffic between client and server.

    sessionStorage:

    • It is similar to localStorage.
    • Changes are only available per window (or tab in browsers like Chrome and Firefox). Changes made are saved and available for the current page, as well as future visits to the site on the same window. Once the window is closed, the storage is deleted The data is available only inside the window/tab in which it was set.

    • The data is not persistent i.e. it will be lost once the window/tab is closed. Like localStorage, it works on same-origin policy. So, data stored will only be available on the same origin.

    0 讨论(0)
  • 2020-11-22 03:52

    OK, LocalStorage as it's called it's local storage for your browsers, it can save up to 10MB, SessionStorage does the same, but as it's name saying, it's session based and will be deleted after closing your browser, also can save less than LocalStorage, like up to 5MB, but Cookies are very tiny data storing in your browser, that can save up 4KB and can be accessed through server or browser both...

    I also created the image below to show the differences at a glance:

    0 讨论(0)
提交回复
热议问题