有時需要將網頁中的一些數據保存在瀏覽器端,這樣做的好處是,當下次訪問頁面時,不需要再次向服務器請求數據,直接就可以從本地讀取數據。目前常用的有以下幾種方法:
cookie
cookie會隨着每次HTTP請求頭信息一起發送,無形中增加了網絡流量,另外,cookie能存儲的數據容量有限,根據瀏覽器類型不同而不同,IE6大約只能存儲2K。
Flash ShareObject
這種方式能能解決上面提到的cookie存儲的兩個弊端,而且能夠跨瀏覽器,應該說是目前最好的本地存儲方案。不過,需要在頁面中插入一個Flash,當瀏覽器沒有安裝Flash控件時就不能用了。所幸的是,沒有安裝Flash的用戶極少。
缺點:需要安裝Flash插件。
Google Gear
Google開發出的一種本地存儲技術。
缺點:需要安裝Gear組件。
userData
IE瀏覽器可以使用userData來存儲數據,容量可達到640K,這種方案是很可靠的,不需要安裝額外的插件。缺點:它僅在IE下有效。
sessionStorage
使用於Firefox2+的火狐瀏覽器,用這種方式存儲的數據僅窗口級別有效,同一個窗口(或者Tab)頁面刷新或者跳轉,都能獲取到本地存儲的數據,當新開窗口或者頁面時,原來的數據就失效了。
缺點:IE不支持、不能實現數據的持久保存。
globalStorage
使用於Firefox2+的火狐瀏覽器,類似於IE的userData。
JAVASCRIPT:
//賦值 globalStorage[location.hostname]['name'] = 'tugai'; //讀取 globalStorage[location.hostname]['name']; //刪除 globalStorage[location.hostname].removeItem('name');
缺點:IE不支持。
localStorage
localStorage是Web Storage互聯網存儲規范中的一部分,現在在Firefox 3.5、Safari 4和IE8中得到支持。
缺點:低版本瀏覽器不支持。
結論:
Flash shareobject是不錯的選擇,如果你不想在頁面上嵌入Flash,可以結合使用userData(IE6+)和globalStorage(Firefox2+)和localStorage(chrome3+)實現跨瀏覽器。
補充:由於項目需要,簡單模擬了HTML5 localStorage中的幾個方法,支持firefox2+,IE5+,chrome3+,其他不詳。
JAVASCRIPT:
if (!('localStorage' in window)) { window.localStorage = (function() { var documentElement, isIE = !!document.all; if (isIE) { documentElement = document.documentElement; documentElement.addBehavior('#default#userdata'); } return { setItem: function(key, value) { if (isIE) { documentElement.setAttribute('value', value); documentElement.save(key); } else { window.globalStorage[location.hostname][key] = value; } }, getItem: function(key) { if (isIE) { documentElement.load(key); return documentElement.getAttribute('value'); } return window.globalStorage[location.hostname][key]; }, removeItem: function(key) { if (isIE) { documentElement.removeAttribute('value'); documentElement.save(key); } else { window.globalStorage[location.hostname].removeItem(key); } } }; })(); } //寫入 localStorage.setItem('name', 'shuiniuer'); //讀取 localStorage.getItem('name'); //刪除 localStorage.removeItem('name');