很多時候我們做web開發往cookie里面存數據,只是為了在不同的網頁之間跳轉的時候可以共享數據,但是cookie里面的每個數據不管是否需要都會在每個同域的http請求中被發送往服務器,包括每個頁面、圖片、css、腳本或者ajax的的請求,這就無形中占用了多余的帶寬。更糟糕的是,一個網頁的cookie本來也只有有限的4k空間,一旦不小心寫入的cookie超過了限制,就會造成原來有用的cookie丟失,這樣造成的bug非常難以追查。
因此我們在IE下面經常使用userdata來保存共享數據。但是在firefox下面卻一直缺乏對應的特性。
今天在看firefox 2.0的
?的時候,驚奇的發現一個新特性叫做:
Support for client-side session and persistent storage趕緊試驗了一下,firefox2.0果然支持這個特性了。雖然還只能在session生命周期內使用(而不像ie的userdata可以指定有效時間),但是總算解決了cookie占用的問題了。
以前曾經寫過一個只支持ie的
userdata管理器,現在可以升級了:
<!DOCTYPE?HTML?PUBLIC?"-//W3C//DTD?HTML?4.0?Transitional//EN">
<HTML>
<HEAD>
<TITLE>?UserData?manager?</TITLE>
<META?NAME="Generator"?CONTENT="EditPlus">
<META?NAME="Author"?CONTENT="emu">
<META?NAME="Keywords"?CONTENT="IE?USER?DATA?manager">
<META?NAME="Description"?CONTENT="UserData?manager">
</HEAD>
<BODY>
<SCRIPT?LANGUAGE="JavaScript">
<!--
var?isIE?=?!!document.all;
if(isIE)
document.documentElement.addBehavior("#default#userdata");
function??saveUserData(key,?value){
????var?ex;?
????if(isIE){
????????with(document.documentElement)try?{
????????????load(key);
????????????setAttribute("value",?value);
????????????save(key);
????????????return??getAttribute("value");
????????}catch?(ex){
????????????alert(ex.message)
????????}
????}else?if(window.sessionStorage){//for?firefox?2.0+
????????try{
????????????sessionStorage.setItem(key,value)
????????}catch?(ex){
????????????alert(ex);
????????}
????}else{
????????alert("當前瀏覽器不支持userdata或者sessionStorage特性")
????}
}
function?loadUserData(key){
????var?ex;?
????if(isIE){
????????with(document.documentElement)try{
????????????load(key);
????????????return?getAttribute("value");
????????}catch?(ex){
????????????alert(ex.message);return?null;
????????}
????}else?if(window.sessionStorage){//for?firefox?2.0+
????????try{
????????????return?sessionStorage.getItem(key)
????????}catch?(ex){
????????????alert(ex)
????????}
????}else{
????????alert("當前瀏覽器不支持userdata或者sessionStorage特性")
????}
}
function??deleteUserData(key){
????var?ex;?
????if(isIE){
????????with(document.documentElement)try{
????????????load(key);
????????????expires?=?new?Date(315532799000).toUTCString();
????????????save(key);
????????}
????????catch?(ex){
????????????alert(ex.message);
????????}
????}else?if(window.sessionStorage){//for?firefox?2.0+
????????try{
????????????sessionStorage.removeItem(key)
????????}catch?(ex){
????????????alert(ex)
????????}
????}else{
????????alert("當前瀏覽器不支持userdata或者sessionStorage特性")
????}
}?
saveUserData("emu","hello?world?!")
alert(loadUserData("emu"))
deleteUserData("emu")
alert(loadUserData("emu"))
//-->
</SCRIPT>
</BODY>
</HTML>
這個特性不能在本地網頁上試驗,必須把頁面用某個服務器(apache或者iis都可以)發布后用firefox訪問。