Window.localStorage

翻譯不完整。 請幫助我們翻譯這篇文章!

localStorage 為一唯讀屬性, 此屬性允許您存取目前文件(Document)隸屬網域來源的 Storage 物件; 與 sessionStorage 不同的是其儲存資料的可存取範圍為跨瀏覽頁狀態(Browser Sessions). localStorage 的應用與 sessionStorage 相似, 除了 localStorage 的儲存資料並無到期的限制, 而 sessionStorage 的儲存資料於目前瀏覽頁狀態結束的同時將一併被清除 — 也就是目前瀏覽器頁面被關閉的同時.

值得注意的是不論 localStorage 或者 sessionStorage 皆為專屬於目前瀏覽器頁面的通訊協定(Protocol).

鍵值名稱和值皆為字串型式(請留意, 當其為物件, 整數等將自動轉換為字串型式).

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 ≤37Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 11Safari iOS Full support 3.2Samsung Internet Android Full support 1.0

Legend

Full support  
Full support

See also