点评:html5中的Web Storage包括了两种存储方式:sessionStorage和localStorage。sessionStorage用于本地存储一个会话(session)中的数据,这些数据只有在同一个会话中的页面才能访问并且当会话结束后数据也随之销毁
因此sessionStorage不是一种持久化的本地存储,仅仅是会话级别的存储。而localStorage用于持久化的本地存储,除非主动删除数据,否则数据是永远不会过期的。复制代码
代码如下:if(window.localStorage){
alert("浏览支持localStorage")
}
else
{
alert("浏览暂不支持localStorage")
}
//或者 if(typeof window.localStorage == 'undefined'){ alert("浏览暂不支持localStorage") }
复制代码
代码如下:sessionStorage.setItem("key", "value");
localStorage.setItem("site", "js8.in");
复制代码
代码如下:var value = sessionStorage.getItem("key");
var site = localStorage.getItem("site");
复制代码
代码如下:sessionStorage.removeItem("key");
localStorage.removeItem("site");
复制代码
代码如下:sessionStorage.clear();
localStorage.clear();
复制代码
代码如下:
var storage = window.localStorage; storage.key1 = "hello";
storage["key2"] = "world";
console.log(storage.key1);
console.log(storage["key2"]);
复制代码
代码如下:
var storage = window.localStorage;
for (var i=0, len = storage.length; i < len; i++)
{
var key = storage.key(i);
var value = storage.getItem(key);
console.log(key + "=" + value);
}
复制代码
代码如下:if(window.addEventListener){
window.addEventListener("storage",handle_storage,false);
}
else if(window.attachEvent)
{
window.attachEvent("onstorage",handle_storage);
}
function handle_storage(e){
if(!e){e=window.event;}
}
PropertyTypeDescription
keyStringThe named key that was added, removed, or moddified
oldValueAnyThe previous value(now overwritten), or null if a new item was added
newValueAnyThe new value, or null if an item was added
url/uriStringThe page that called the method that triggered this change
新闻热点
疑难解答