Window.localStorage

This translation is incomplete. Please help translate this article from English

localStorage 這個唯讀屬性允許你讀取 Storage object for the Document's origin; 被儲存的資料被存在 across browser sessions. localStoragesessionStorage大致上相似,除了儲存在 localStorage 內的資料沒有逾期時間外,當頁面session結束時,存在 sessionStorage 內的資料就會被清空 — 也就是當頁面被關閉的時候。

It should be noted that data stored in either localStorage or sessionStorage is specific to the protocol of the page.

鍵 值The keys and the values are always strings (note that, as with objects, 整數的鍵/值將會被自動轉換成字串)

Syntax

myStorage = window.localStorage;

Value

Storage 物件 which can be used to access the current origin's local storage space.

Exceptions

SecurityError
The request violates a policy decision, or the origin is not a valid scheme/host/port tuple (this can happen if the origin uses the file: or data: scheme, for example). 舉例來說,使用者 may have their browser configured to deny permission to persist data for the specified origin.

Example

下列的程式碼片段讀取了目前域名內的 local Storage 物件 ,並用Storage.setItem(),增加一個資料物件 item 到其中

localStorage.setItem('myCat', 'Tom');

讀取 localStorage 內物件的語法如下:

var cat = localStorage.getItem('myCat');

移除 localStorage 內物件的語法如下:

localStorage.removeItem('myCat');

刪除 localStorage 內所有物件的語法如下:

// Clear all items
localStorage.clear();

Note: Please refer to the Using the Web Storage API article for a full example.

Specifications

Specification Status Comment
HTML Living Standard
The definition of 'localStorage' in that specification.
Living Standard

瀏覽器相容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
localStorageChrome Full support 4Edge Full support 12Firefox Full support 3.5IE Full support 8Opera Full support 10.5Safari Full support 4WebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support 11Safari iOS Full support 3.2Samsung Internet Android Full support Yes

Legend

Full support  
Full support

See also