1. 程式人生 > 實用技巧 >Web technology for developersSee Web APIsStorage

Web technology for developersSee Web APIsStorage

Storage

TheStorageinterface of theWeb Storage APIprovides access to a particular domain's session or local storage. It allows, for example, the addition, modification, or deletion of stored data items.

To manipulate, for instance, the session storage for a domain, a call toWindow.sessionStorageis made; whereas for local storage the call is made to

Window.localStorage.

Window.sessionStorage

ThesessionStorageproperty accesses a sessionStorageobject for the current origin.sessionStorageis similar tolocalStorage; the difference is that while data inlocalStoragedoesn't expire, data insessionStorageis cleared when thepage sessionends.

  • A page session lasts as long as the browser is open, and survives over page reloads and restores.
  • Opening a page in a new tab or window creates a new session with the value of the top-level browsing context, which differs from how session cookies work.
  • Opening multiple tabs/windows with the same URL createssessionStoragefor each tab/window.
  • Closing a tab/window ends the session and clears objects insessionStorage
    .

Window.localStorage

The read-onlylocalStorageproperty allows you to access aStorageobject for theDocument's origin; the stored data is saved across browser sessions.localStorageis similar tosessionStorage, except that while data stored inlocalStoragehas no expiration time, data stored insessionStoragegets cleared when the page session ends — that is, when the page is closed. (Data in alocalStorageobject created in a "private browsing" or "incognito" session is cleared when the last "private" tab is closed.)

Data stored in eitherlocalStorageorsessionStorageis specific to the protocol of the page. In particular, data stored by a script on a site accessed with HTTP (e.g.,http://example.com) is put in a differentlocalStorageobject from the same site accessed with HTTPS (e.g.,https://example.com).

The keys and the values arealwaysin the UTF-16DOMStringformat, which uses two bytes per character. (As with objects, integer keys are automatically converted to strings.)