Fork me on GitHub

html5 web存储

以前客户端存储数据都是由 cookie 完成的。但是 cookie 不适合大量数据的存储,因为它们由每个对服务器的请求来传递,这使得 cookie 速度很慢而且效率也不高。
HTML5 提供了两种在客户端存储数据的新方法:localStorage& sessionStorage

localStorage - 没有时间限制的数据存储

localStorage 方法存储的数据没有时间限制。

基本用法
  • 存值 localStorage.setItem(key,value) [如果key的value存在时,更新key的值]

    1
    2
        localStorage.name = "123"; 
     localStorage["name"] = "123";
  • 取值 localStorage.getItem(key,value) [如果key的value不存在时,返回null]

    1
    2
    var name = localStorage.name;
    var name = localStorage["name"];
  • 删除 localStorage.remove(key) [清除单项key的值]
  • 清除 localStorage.clear() [表示清除localStorage存储的所有数据]
补充

当需要存储的数据很多时,可以将数据存储到数组中并转换成JSON格式的数据。

  1. JSON.stringify(data) 将对象转换成JSON格式的数据串。
  2. JSON.parse(data)将数据解析成对象并返回解析后的对象。
1
2
3
var arr = {"name":"moomoo","age":2,"eat":"apple"};
localStorage.setItem("arr",JSON.stringify(arr));
arr = JSON.parse(localStorage.getItem("arr"));
说明

localStorage存储的数据是不能跨浏览器共用的,也就是说存储在浏览器的数据只能在这个浏览器中访问,现在各个浏览器的存储空间是5M。

sessionStorage - 针对一个 session 的数据存储

sessionStorage是个全局对象,它维护着在页面会话(page session)期间有效的存储空间。只要浏览器开着,页面会话周期就会一直持续。当页面重新载入(reload)或者被恢复(restores)时,页面会话也是一直存在的。每在新标签或者新窗口中打开一个新页面,都会初始化一个新的会话,也就是说sessionStorage针对一个 session 进行数据存储。当用户关闭浏览器窗口后,数据会被删除。

当浏览器被意外刷新的时候,一些临时数据应当被保存和恢复。sessionStorage 对象在处理这种情况的时候是最有用的。sessionStorage自动保存一个文本域中的内容,如果浏览器被意外刷新,则恢复该文本域中的内容,所以不会丢失任何输入的数据。

基本用法

sessionStorage 方法与localStorage的方法相似

兼容性

并不是所有的浏览器都支持。如果你想在没有原生支持localStorage对象的浏览器中使用它,可以在你编写的 JavaScript代码的首部插入下面两段代码中的任意一段。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
if (!window.localStorage) {
Object.defineProperty(window, "localStorage", new (function () {
var aKeys = [], oStorage = {};
Object.defineProperty(oStorage, "getItem", {
value: function (sKey) { return sKey ? this[sKey] : null; },
writable: false,
configurable: false,
enumerable: false
});
Object.defineProperty(oStorage, "key", {
value: function (nKeyId) { return aKeys[nKeyId]; },
writable: false,
configurable: false,
enumerable: false
});
Object.defineProperty(oStorage, "setItem", {
value: function (sKey, sValue) {
if(!sKey) { return; }
document.cookie = escape(sKey) + "=" + escape(sValue) + "; path=/";
},
writable: false,
configurable: false,
enumerable: false
});
Object.defineProperty(oStorage, "length", {
get: function () { return aKeys.length; },
configurable: false,
enumerable: false
});
Object.defineProperty(oStorage, "removeItem", {
value: function (sKey) {
if(!sKey) { return; }
var sExpDate = new Date();
sExpDate.setDate(sExpDate.getDate() - 1);
document.cookie = escape(sKey) + "=; expires=" + sExpDate.toGMTString() + "; path=/";
},
writable: false,
configurable: false,
enumerable: false
});
this.get = function () {
var iThisIndx;
for (var sKey in oStorage) {
iThisIndx = aKeys.indexOf(sKey);
if (iThisIndx === -1) { oStorage.setItem(sKey, oStorage[sKey]); }
else { aKeys.splice(iThisIndx, 1); }
delete oStorage[sKey];
}
for (aKeys; aKeys.length > 0; aKeys.splice(0, 1)) { oStorage.removeItem(aKeys[0]); }
for (var iCouple, iKey, iCouplId = 0, aCouples = document.cookie.split(/\s*;\s*/); iCouplId < aCouples.length; iCouplId++) {
iCouple = aCouples[iCouplId].split(/\s*=\s*/);
if (iCouple.length > 1) {
oStorage[iKey = unescape(iCouple[0])] = unescape(iCouple[1]);
aKeys.push(iKey);
}
}
return oStorage;
};
this.configurable = false;
this.enumerable = true;
})());
}

或者

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
if (!window.localStorage) {
window.localStorage = {
getItem: function (sKey) {
if (!sKey || !this.hasOwnProperty(sKey)) { return null; }
return unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"), "$1"));
},
key: function (nKeyId) { return unescape(document.cookie.replace(/\s*\=(?:.(?!;))*$/, "").split(/\s*\=(?:[^;](?!;))*[^;]?;\s*/)[nKeyId]); },
setItem: function (sKey, sValue) {
if(!sKey) { return; }
document.cookie = escape(sKey) + "=" + escape(sValue) + "; path=/";
this.length = document.cookie.match(/\=/g).length;
},
length: 0,
removeItem: function (sKey) {
if (!sKey || !this.hasOwnProperty(sKey)) { return; }
var sExpDate = new Date();
sExpDate.setDate(sExpDate.getDate() - 1);
document.cookie = escape(sKey) + "=; expires=" + sExpDate.toGMTString() + "; path=/";
this.length--;
},
hasOwnProperty: function (sKey) { return (new RegExp("(?:^|;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie); }
};
window.localStorage.length = (document.cookie.match(/\=/g) || window.localStorage).length;
}

本文标题:html5 web存储

文章作者:tongtong

发布时间:2018年04月26日 - 12:04

最后更新:2019年03月15日 - 11:03

原始链接:https://ilove-coding.github.io/2018/04/26/html5-web存储/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

坚持原创技术分享,您的支持将鼓励我继续创作!
-------------本文结束-------------