復制代碼代碼如下: if(typeof(Storage)!=="undefined"){ // Yes! localStorage and sessionStorage support! // Some code..... } else { // Sorry! No web storage support.. }
第二種方式就是分別檢查各自的對象,例如檢查localStorage是否支持:
復制代碼代碼如下: if (typeof(localStorage) == 'undefined' ) { alert('Your browser does not support HTML5 localStorage. Try upgrading.'); } else { // Yes! localStorage and sessionStorage support! // Some code..... } 或者: if('localStorage' in window window['localStorage'] !== null){ // Yes! localStorage and sessionStorage support! // Some code..... } else { alert('Your browser does not support HTML5 localStorage. Try upgrading.'); } 或者 if (!!localStorage) { // Yes! localStorage and sessionStorage support! // Some code..... } else { alert('Your browser does not support HTML5 localStorage. Try upgrading.'); }
很顯然第一個方式最直接,也最簡單。 Web Storage的使用 Web Storage中存儲的是鍵值對,而且瀏覽器會以字符串方式存儲。記住在必要的時候將他們轉為其他格式。 sessionStorage與localStorage除了用途不同外,成員列表是一樣的:
復制代碼代碼如下: try { localStorage.setItem(itemId, values.join(';')); } catch (e) { if (e == QUOTA_EXCEEDED_ERR) { alert('Quota exceeded!'); } }
Web Storage的方法非常簡單,下面的示例是統(tǒng)計button點擊的次數(shù)的:
復制代碼代碼如下: !DOCTYPE html html head script function clickCounter() { if(typeof(Storage)!=="undefined") { if (localStorage.clickcount) { localStorage.clickcount=Number(localStorage.clickcount)+1; } else { localStorage.clickcount=1; } document.getElementById("result").innerHTML="You have clicked the button " + localStorage.clickcount + " time(s)."; } else { document.getElementById("result").innerHTML="Sorry, your browser does not support web storage..."; } } /script /head body p button type="button" Click me! /button /p div id="result" /div p Click the button to see the counter increase. /p p Close the browser tab (or window), and try again, and the counter will continue to count (is not reset). /p /body /html