如何使用 HTML5 localStorage API 將資料儲存在瀏覽器中?
HTML5 localStorage 在瀏覽器中儲存字串資料,並且在當前會話之後仍然存在。localStorage 儲存資料,沒有到期時間,而 sessionStorage 僅限於僅限當前會話。當瀏覽器關閉時,會話將丟失。
本地儲存旨在用於跨多個視窗並超過當前會話的儲存。特別是,Web 應用程式可能希望出於效能原因,在客戶端儲存兆位元組的使用者資料,例如整個使用者建立的文件或使用者的郵箱。
您可以嘗試執行以下程式碼,以瞭解如何使用 HTML5 localStorage
示例
<!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 on the website:" + 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>
廣告