HTML Web Storage

Web Storage API的出现,使得开发者可以将需要跨请求重复访问的数据直接存储在客户端的浏览器中,还可以在关闭浏览器很久再次打开时恢复数据,以减小网络流量。


Cookies vs. Local Storage

在H5之前,应用数据通常存储在cookie中。服务器可以基于其放在cookie中的数据在不同Web页面间追踪用户的信息。用户每次访问某个域时,cookie数据都会被来回传送。

When a browser request a web page from a server, cookies belonging to the page is added to the request. This way the server gets the necessary data to "remember" information about users.

1. Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.

与cookies(只能设置大约4KB多数据,只要有请求涉及cookie,cookie就要在服务器和浏览器间来回传送)不同的是,LS的存储极限更大,且存储的数据不会在网络上传输。

2. 如果用户使用设置为“私有/隐私保护”模式的浏览器进行浏览,那么在浏览器关闭后,localStorage中的值将不会保存。因为使用了这种模式的用户已经明确选择不留痕迹。

3. sessionStorage,数据只在构建它们的窗口或标签内可见。localStorage,数据可以被同源的每个窗口或标签页共享。

4. Storage接口方法key(index)允许获取一个指定位置的键。获取键后,可以用它来获得相应的数据。

5. removeItem(key)函数用来删除数据项。删除数据相时,不会将原有数据作为返回结果,与某些集和或数据框架不同。

6. clear() 函数删除存储列表中所有的数据,空的Storage对象调用此函数也是安全的,只是不执行任何操作。 

7. 如果用户已关闭了网站的存储,或存储达到其最大的容量,此时设置数据将抛出QUOTA_EXCEEDED_ERR错误。

8. 只要有同源的Storage事件发生(包括SessionStorage和LocalStorage触发的事件),已注册的所有事件侦听器作为事件处理程序就会接到相应的Storage事件。该事件中包含与存储变化有关的信息。如果是新添加的数据,则oldValue属性值为null,如果是被删除的数据,则newValue属性值为null。


Web Storage Objects

HTML WS 提供了两种对象用来在客户端存储数据:

  • window.localStorage - stores data with no expiration date (数据不会因为浏览器关闭而删除,如没有干预,将一直有效)
  • window.sessionStorage - stores data for one session (data is lost when the tab is closed)

通常我们可以省略window对象,因为storage对象可以从默认的页面上下文中获得。

使用前先检查一下浏览器对WS的支持性:

if(window.localStorage/window.sessionStorage) {
    // Code for localStorage/sessionStorage.
} else {
    // Sorry! No Web Storage support..
}

localStorage

存储和获取:

// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
另一种写法:

// Store
localStorage.lastname = "Smith";
localStorage['lastname'] = "Smith";
// Retrieve
document.getElementById("result").innerHTML = localStorage.lastname;
删除:
localStorage.removeItem("lastname");

Note: Name/value pairs are always stored as strings. Remember to convert them to another format when needed!

需要注意的是,键/值 对总是以字符串形式存储,使用时根据需要进行格式转换。

if (localStorage.clickcount) {
    localStorage.clickcount = Number(localStorage.clickcount) + 1;
} else {
    localStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
localStorage.clickcount + " time(s).";

sessionStorage

该对象等同于 localStorage,除了它只为一个浏览器会话存储数据,也就是说,当浏览器窗口关闭时,数据就被删除。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值