1. 浏览器支持
userData是微软为IE在系统中开辟的存储空间。因此只支持windows+IE。意外的是从IE5.5就已经开始userData了。
2. 大小限制
Local Machine 1281024
Intranet 512 10240
Trusted Sites 1281024
Internet 128 1024
Restricted 64 640
线上使用时,单个文件大小限制为128KB,一个域名下文件大小限制为1024KB,文件数应该没有限制。在受限站点里这两个值分别是64KB和640KB,所以如果考虑到各种情况的话,单个文件最好能控制64KB以下。
3. 使用
官方文档还加了说明:
Setting the userData behavior class on the html, head, title, or style object causes an error when the save or load method is called.
apply to:
A, ABBR, ACRONYM, ADDRESS, AREA, B, BIG, BLOCKQUOTE, BUTTON, CAPTION, CENTER, CITE, CODE, DD, DEL, DFN, DIR, DIV, DL, DT, EM, FONT, FORM, hn, HR, I, IMG, INPUT type=button, INPUT type=checkbox, INPUT type=file, INPUT type=hidden, INPUT type=image, INPUT type=password, INPUT type=radio, INPUT type=reset, INPUT type=submit, INPUT type=text, KBD, LABEL, LI, LISTING, MAP, MARQUEE, MENU, OBJECT, OL, OPTION, P, PLAINTEXT, PRE, Q, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TEXTAREA, TT, U, UL, VAR, XMP
可以使用style方式也可以用js来创建支持userData的对象。
html方式
js创建
o=document.createElement(‘input’);
o.type=’hidden’;
o.addBehavior(‘#default#userData’);
//等同于 o.style.behavior=”url(‘#default#userData’)”;
document.body.appendChild(o);
属性
XMLDocument 读取文件的XML DOM
方法
load 打开文件
removeAttribute 删除指定的属性
save 保存文件
setAttribute 为指定属性赋值
4. 目录限制
http://example.com/path1
只能是http://example.com/path1/example.php目录下网页文件才可访问 。
而http://example.com/path1/path2目录下所有文件是访问不到path1保存的数据的。
5. 封装
不想再自己写了,下面是来自sofish.de的代码:
typeof window.localStorage == 'undefined' && ~function() {
var localStorage = window.localStorage = {},
prefix = 'data-userdata',
doc = document,
attrSrc = doc.body,
html = doc.documentElement,
mark = function(key, isRemove, temp, reg) {
html.load(prefix);
temp = html.getAttribute(prefix);
reg = RegExp('\\b' + key + '\\b,?', 'i');
hasKey = reg.test(temp) ? 1 : 0;
temp = isRemove ? temp.replace(reg, '').replace(',', '') : hasKey ? temp : temp === '' ? key : temp.split(',').concat(key).join(',');
html.setAttribute(prefix, temp);
html.save(prefix);
};
attrSrc.addBehavior('#default#userData');
html.addBehavior('#default#userData');
localStorage.getItem = function(key) {
attrSrc.load(key);
return attrSrc.getAttribute(key);
};
localStorage.setItem = function(key, value) {
attrSrc.setAttribute(key, value);
attrSrc.save(key);
mark(key);
};
localStorage.removeItem = function(key) {
attrSrc.removeAttribute(key);
attrSrc.save(key);
mark(key, 1);
};
localStorage.clear = function() {
html.load(prefix);
var attrs = html.getAttribute(prefix).split(','),
len = attrs.length;
for(var i=0 ; i<len ; i++) {
attrSrc.removeAttribute(attrs[i]);
attrSrc.save(attrs[i]);
};
html.setAttribute(prefix, '');
html.save(prefix);
};
}();
原文地址:http://mao.li/cross-browser-local-storage-with-userdata-and-localstorage/