在看LocalStorage的时候发现了一件神奇的事情
IE8居然已经就支持了..
操作很简单就4个
1 <script type="text/javascript"> 2 localStorage.setItem("test", "测试中"); 3 alert(localStorage.getItem("test")); 4 5 localStorage.setItem("test1", "测试1"); 6 alert(localStorage.getItem("test1")); 7 8 localStorage.setItem("test", "测试中1"); //修改test 9 alert(localStorage.getItem("test")); 10 11 localStorage.removeItem("test1"); 12 alert(localStorage.getItem("test1")); //返回null 13 14 localStorage.clear(); 15 alert(localStorage.getItem("test")); //返回null 16 </script>
既然是键值对. 得到key的方法自然也必须有
1 for (var i = 0; i < localStorage.length; i++) 2 { 3 alert(localStorage.key(i)); 4 alert(localStorage.getItem(localStorage.key(i))); 5 }
localStorage提供了方法监听localStorage,当其他页面改变localStorage的时候(IE当前页面也可以),触发事件
var Storage = { _storage: null, _errorText : null, _enum: { Success: 0, Browser: 1, OtherError : 99 }, /* 得到localStorage @static @return {window.localStorage} */ _getStorage: function () { if (this._storage) return this._storage; if (!!window.localStorage) { this._storage = window.localStorage; } else { this._errorText = this._enum.Browser; } return this._storage; }, /* 是否可用 @static @return {Bool} */ isAvailable: function () { return !!(this._getStorage()); }, /* 得到错误码 @return {string} */ getErrorCode:function() { return this._errorText; }, /** 写入数据 @static @param {string} key @param {string} val @return {bool} */ setItem: function (key, val) { var st = this._getStorage(); return st && st.setItem(key, val); }, /* 读取数据 @static @param {string} key @return {bool} */ getItem: function (key) { var st = this._getStorage(); return st && st.getItem(key); }, /* 删除数据 @static @param {string} key @return {bool} */ removeItem: function (key) { var st = this._getStorage(); return st && st.removeItem(key); }, /** 清空 @static @return {bool} */ clear: function () { var st = this._getStorage(); return st && st.clear(); }, /* 监听某个key的变化 @param {string} key 需要监听的key @param {string} callback 当数据发生变化时的回调(回调中传入的参数为当前key对应的值) @return {bool} */ onstorage: function (key, callback) { var st = this._getStorage(); if (document.attachEvent && !K.Browser.opera) { document.attachEvent("onstorage", this._onstorage(key, callback,st)); } //其他注册在window上 else { window.addEventListener("storage", this._onstorage(key, callback,st), false); }; }, _onstorage: function (key, callback,st) { var oldValue = st[key]; /* 会执行3次 所以需要判断是否和oldValue一致 */ return function (e) { setTimeout(function () { if (key == e.key && oldValue != e.newValue) { alert("key:" + e.key + ", newValue:" + e.newValue + ",oldValue : " + oldValue + ", Url:" + window.location.href); oldValue = e.newValue; } }, 0); }; } }
webIM 就不用那么苦逼的 一次又一次的去轮训了.
SessionStorage 用法差不多,不过是在浏览器关闭时会销毁。
本地存储这东西并不安全, 就opera 有过简单加密,其他的都是明文的.
很容易遭受xxs攻击,如果是你对你们过滤没信心的话..
不要存储敏感信息.