HTML5 引入了兩種機制,類似于 HTTP 的會話 cookies,用于在客戶端存儲結構化數(shù)據(jù)以及克服以下缺點。
每個 HTTP 請求中都包含 Cookies,從而導致傳輸相同的數(shù)據(jù)減緩我們的 Web 應用程序。
每個 HTTP 請求中都包含 Cookies,從而導致發(fā)送未加密的數(shù)據(jù)到互聯(lián)網(wǎng)上。
這兩種存儲方式是 session storage 和 local storage,它們將用于處理不同的情況。
幾乎所有最新版的瀏覽器都支持 HTML5 存儲,包括 IE 瀏覽器。
_會話存儲_被設計用于用戶執(zhí)行單一事務的場景,但是同時可以在不同的窗口中執(zhí)行多個事務。
比如,如果用戶在同一網(wǎng)站的兩個不同的窗口中購買機票。如果該網(wǎng)站使用 cookie 跟蹤用戶購買的機票,當用戶在窗口中點擊頁面時,從一個窗口到另一個時當前已經(jīng)購買的機票會“泄漏”,這可能導致用戶購買同一航班的兩張機票而沒有注意到。
HTML5 引入了 sessionStorage 屬性,這個網(wǎng)站可以用來把數(shù)據(jù)添加到會話存儲中,用戶仍然可以在打開的持有該會話的窗口中訪問同一站點的任意頁面,當關閉窗口時,會話也會丟失。
下面的代碼將會設置一個會話變量,然后訪問該變量:
<!DOCTYPE HTML>
<html>
<body>
<script type="text/javascript">
if( sessionStorage.hits ){
sessionStorage.hits = Number(sessionStorage.hits) +1;
}else{
sessionStorage.hits = 1;
}
document.write("Total Hits :" + sessionStorage.hits );
</script>
<p>Refresh the page to increase number of hits.</p>
<p>Close the window and open it again and check the result.</p>
</body>
</html>
便于學習上面的概念 - 請進行在線練習。
_本地存儲_被設計用于跨多個窗口進行存儲,并持續(xù)處在當前會話上。尤其是,出于性能的原因 Web 應用程序可能希望在客戶端存儲百萬字節(jié)的用戶數(shù)據(jù),比如用戶撰寫的整個文檔或者是用戶的郵箱。
Cookies 并不能很好的處理這種情況,因為每個請求都會傳輸。
HTML5 引入了 localStorage 屬性,可以用于訪問頁面的本地存儲區(qū)域而沒有時間限制,無論何時我們使用這個頁面的時候本地存儲都是可用的。
下面的代碼設置了一個本地存儲變量,每次訪問這個頁面時都可以訪問該變量,甚至是下次打開窗口時:
<!DOCTYPE HTML>
<html>
<body>
<script type="text/javascript">
if( localStorage.hits ){
localStorage.hits = Number(localStorage.hits) +1;
}else{
localStorage.hits = 1;
}
document.write("Total Hits :" + localStorage.hits );
</script>
<p>Refresh the page to increase number of hits.</p>
<p>Close the window and open it again and check the result.</p>
</body>
</html>
便于學習上述概念 - 請進行在線練習。
在本地機器上存儲敏感數(shù)據(jù)可能是危險的,可能會留下安全隱患。
_會話存儲數(shù)據(jù)_在會話終止之后將由瀏覽器立即刪除。
要清除本地存儲設置需要調(diào)用 localStorage.remove('key');這個 'key' 就是我們想要移除的值對應的鍵。如果想要清除所有設置,需要調(diào)用 localStorage.clear() 方法。
下面的代碼會完全清除本地存儲:
<!DOCTYPE HTML>
<html>
<body>
<script type="text/javascript">
localStorage.clear();
// Reset number of hits.
if( localStorage.hits ){
localStorage.hits = Number(localStorage.hits) +1;
}else{
localStorage.hits = 1;
}
document.write("Total Hits :" + localStorage.hits );
</script>
<p>Refreshing the page would not to increase hit counter.</p>
<p>Close the window and open it again and check the result.</p>
</body>
</html>
便于學習上述概念 - 請進行在線練習。