时间:2021-07-01 10:21:17 帮助过:42人阅读
2.浏览器支持检测
function checkStorageSupport() { //sessionStorage if (window.sessionStorage) { alert('This browser supports sessionStorage'); } else { alert('This browser does NOT support sessionStorage'); } //localStorage if (window.localStorage) { alert('This browser supports localStorage'); } else { alert('This browser does NOT support localStorage'); } }
3.Storage接口
interface Storage { //同源键值对的数目 readonly attribute unsigned long length; //通过索引获取键,索引从0开始 getter DOM String key (in unsigned long index); //通过键获取值,键若不存在,值将返回 null getter any getItem(in DOMString key); //存储键值对,若已存在同名键,则值将被覆盖。若用户关闭了浏览器存储或是已超 //过允许存储的最大值,都将产生QUOTA_EXCEEDED_ERR错误。 set ter creator void setItem(in DOMString key, in any data); //通过键删除值,不存在则什么也不做 delete r void removeItem(in DOMString key); //删除storage中所有键值对,若为空则什么也不做 void clear (); };
4.读取和存储数据
//---------------方式一-------------- //存储数据 window.sessionStorage.setItem(‘myFirstKey’, ‘myFirstValue’); //读取数据 alert(window.sessionStorage.getItem(‘myFirstKey’)); //---------------方式二-------------- //存储数据 window.sessionStorage.myFirstKey = ‘myFirstValue’; //读取数据 alert(window.sessionStorage.myFirstKey); //---------------方式三-------------- var varKey = sessionStorage.key(index); window.sessionStorage[varKey] = new Value;
5.存储事件
Web Storage与其它页面、浏览器窗口或选项卡、Web Worker间的通信可以通过存储事件来进行。同源的对象都可以监听storage事件。添加storage事件监听方法如下:
window.addEventListener("storage", displayStorageEvent, true);
6.StorageEvent接口
storage事件对象实现了StorageEvent接口,该接口的声明如下:
interface StorageEvent : Event { readonly attribute DOMString key; readonly attribute any oldValue; readonly attribute any newValue; readonly attribute DOMString url; //该方法提供了一个对发生storage事件对象的 引用 ,这个对象可以是 //sessionStorage或localStorage readonly attribute Storage storageArea; };
6.处理最大配额
多数浏览器所允许的Web Storage不超过5MB,为了防止存储数据时产生超出配额的限制,可以使用捕获QUOTA_EXCEEDED_ERR异常的方法来处理,例如:
try { sessionStorage["name"] = "Tabatha"; } catch ( exception ) { if (exception == QUOTA_EXCEEDED_ERR) { // we should tell the user their quota has been exceeded. } }
以上就是HTML5-Web Storage APIs的简述的详细内容,更多请关注Gxl网其它相关文章!