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

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

    The Web Storage API provides mechanisms by which browsers can securely store key/value pairs, in a much more intuitive fashion than using cookies. The Web Storage API extends the Window object with two new properties — Window.sessionStorage and Window.localStorage. — invoking one of these will create an instance of the Storage object, through which data items can be set, retrieved, and removed. A different Storage object is used for the sessionStorage and localStorage for each origin (domain).

    Storage objects are simple key-value stores, similar to objects, but they stay intact through page loads.

    localStorage.colorSetting = '#a4509b';
    localStorage['colorSetting'] = '#a4509b';
    localStorage.setItem('colorSetting', '#a4509b');
    

    The keys and the values are always strings. To store any type convert it to String and then store it. It's always recommended to use Storage interface methods.

    var testObject = { 'one': 1, 'two': 2, 'three': 3 };
    // Put the object into storage
    localStorage.setItem('testObject', JSON.stringify(testObject));
    // Retrieve the object from storage
    var retrievedObject = localStorage.getItem('testObject');
    console.log('Converting String to Object: ', JSON.parse(retrievedObject));
    

    The two mechanisms within Web Storage are as follows:

    • sessionStorage maintains a separate storage area for each given originSame-origin policy that's available for the duration of the page session (as long as the browser is open, including page reloads and restores).
    • localStorage does the same thing, but persists even when the browser is closed and reopened.

    Storage « Local storage writes the data to the disk, while session storage writes the data to the memory only. Any data written to the session storage is purged when your app exits.

    The maximum storage available is different per browser, but most browsers have implemented at least the w3c recommended maximum storage limit of 5MB.

    +----------------+--------+---------+-----------+--------+
    |                | Chrome | Firefox | Safari    |  IE    |
    +----------------+--------+---------+-----------+--------+
    | LocalStorage   | 10MB   | 10MB    | 5MB       | 10MB   |
    +----------------+--------+---------+-----------+--------+
    | SessionStorage | 10MB   | 10MB    | Unlimited | 10MB   |
    +----------------+--------+---------+-----------+--------+
    

    Always catch LocalStorage security and quota exceeded errors

    • QuotaExceededError: When storage limits exceeds on this function window.sessionStorage.setItem(key, value);, it throws a "QuotaExceededError" DOMException exception if the new value couldn't be set. (Setting could fail if, e.g., the user has disabled storage for the site, or if the quota has been exceeded.)

      DOMException.QUOTA_EXCEEDED_ERR is 22, example fiddle.

    • SecurityError : Uncaught SecurityError: Access to 'localStorage' is denied for this document.

       CHROME:-Privacy and security « Content settings « Cookies « Block third-party cookies.
      

    StorageEvent « The storage event is fired on a document's Window object when a storage area changes. When a user agent is to send a storage notification for a Document, the user agent must queue a task to fire an event named storage at the Document object's Window object, using StorageEvent.

    Note: For a real world example, see Web Storage Demo. check out the source code

    Listen to the storage event on dom/Window to catch changes in the storage. fiddle.


    Cookies (web cookie, browser cookie) Cookies are data, stored in small text files as name-value pairs, on your computer.

    JavaScript access using Document.cookie

    New cookies can also be created via JavaScript using the Document.cookie property, and if the HttpOnly flag is not set, existing cookies can be accessed from JavaScript as well.

    document.cookie = "yummy_cookie=choco"; 
    document.cookie = "tasty_cookie=strawberry"; 
    console.log(document.cookie); 
    // logs "yummy_cookie=choco; tasty_cookie=strawberry"
    

    Secure and HttpOnly cookies HTTP State Management Mechanism

    Cookies are often used in web application to identify a user and their authenticated session

    When receiving an HTTP request, a server can send a Set-Cookie header with the response. The cookie is usually stored by the browser, and then the cookie is sent with requests made to the same server inside a Cookie HTTP header.

    Set-Cookie: = 
    Set-Cookie: =; Expires=
    

    Session cookies will get removed when the client is shut down. They don't specify the Expires or Max-Age directives.

    Set-Cookie: sessionid=38afes7a8; HttpOnly; Path=/
    

    Permanent cookies expire at a specific date (Expires) or after a specific length of time (Max-Age).

    Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Secure; HttpOnly
    

    The Cookie HTTP request header contains stored HTTP cookies previously sent by the server with the Set-Cookie header. HTTP-only cookies aren't accessible via JavaScript through the Document.cookie property, the XMLHttpRequest and Request APIs to mitigate attacks against cross-site scripting (XSS).

    Cookies are mainly used for three purposes:

    • Session management « Logins, shopping carts, game scores, or anything else the server should remember
    • Personalization « User preferences, themes, and other settings
    • Tracking (Recording and analyzing user behavior) « Cookies have a domain associated to them. If this domain is the same as the domain of the page you are on, the cookies is said to be a first-party cookie. If the domain is different, it is said to be a third-party cookie. While first-party cookies are sent only to the server setting them, a web page may contain images or other components stored on servers in other domains (like ad banners). Cookies that are sent through these third-party components are called third-party cookies and are mainly used for advertising and tracking across the web.

    Cookies were invented to solve the problem "how to remember information about the user":

    • When a user visits a web page, his name can be stored in a cookie.
    • Next time the user visits the page, cookies belonging to the page is added to the request. This way the server gets the necessary data to "remember" information about users.

    GitHubGist Example


    As summary,

    • localStorage persists over different tabs or windows, and even if we close the browser, accordingly with the domain security policy and user choices about quota limit.
    • sessionStorage object does not persist if we close the tab (top-level browsing context) as it does not exists if we surf via another tab or window.
    • Web Storage (session, local) allows us to save a large amount of key/value pairs and lots of text, something impossible to do via cookie.
    • Cookies that are used for sensitive actions should have a short lifetime only.
    • Cookies mainly used for advertising and tracking across the web. See for example the types of cookies used by Google.
    • Cookies are sent with every request, so they can worsen performance (especially for mobile data connections). Modern APIs for client storage are the Web storage API (localStorage and sessionStorage) and IndexedDB.

提交回复
热议问题