使用userData兼容IE6-10,chrome,FF及360等浏览器的本地存储
- 时间:2015年04月02日 15:23:07 来源:魔法猪系统重装大师官网 人气:16649
开发过程中涉及本地存储的使用,IE很多版本都不支持localStorage,没办法,就得兼容使用userData了。废话不说了,看代码:
(function(window){
var LS;
(function(){
var o = document.getElementsByTagName("head")[0],
n = window.location.hostname || "localStorage",
d = new Date(),doc,agent;
//typeof o.addBehavior 在IE6下是object,在IE10下是function,因此这里直接用!判断
if(!o.addBehavior)return;//防止有些浏览器默认禁用localStorage,这里优先考虑userData本地存储
try{ //尝试创建iframe代理
agent = new ActiveXObject('htmlfile');
agent.open();
agent.write('document.w=window;
使用方法很简单:
对外提供全局变量LS
存储:LS.set('userName',"js明哥哥");
读取:LS.get('userName');
删除:LS.remove('userName');
该组件经过本人测试,暂时没发现什么浏览器不支持,可能测试还不够到位,希望大家多多指点。





