Window.localStorage - Web APIs 编辑

The read-only localStorage property allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions. localStorage is similar to sessionStorage, except that while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the page session ends — that is, when the page is closed. (Data in a localStorage object created in a "private browsing" or "incognito" session is cleared when the last "private" tab is closed.)

Data stored in either localStorage is 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 different localStorage object from the same site accessed with HTTPS (e.g., https://example.com).

The keys and the values are always in the UTF-16 DOMString format, which uses two bytes per character. As with objects, integer keys are automatically converted to strings.

Syntax

myStorage = window.localStorage;

Value

A Storage object 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). For example, the user may have their browser configured to deny permission to persist data for the specified origin.

Example

The following snippet accesses the current domain's local Storage object and adds a data item to it using Storage.setItem().

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

The syntax for reading the localStorage item is as follows:

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

The syntax for removing the localStorage item is as follows:

localStorage.removeItem('myCat');

The syntax for removing all the localStorage items is as follows:

localStorage.clear();

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

Specifications

SpecificationStatusComment
HTML Living Standard
The definition of 'localStorage' in that specification.
Living Standard

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:114 次

字数:4827

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文