4.1 localStorage 與 sessionStorage 簡介

在 html5 還沒有出來之前,本機端的儲存方式,使用的是 cookie,但空間有限,大約是 4k 左右。

而 html5 出來之後,多了 localStoragesessionStorage 兩種儲存方式,空間更大,大約 5M,而且使用了 key-value 的儲存方式,使得更有彈性。

localStorage 與 sessionStorage 可使用的相關屬性、方法,兩者是一樣的。

範例:

Web Storage

html5 資料夾底下,建立 web_storage 資料夾,然後在這個資料夾底下,建立 localstorage.htmlsessionstorage.html 內容如下,以便觀察測試。

<!DOCTYPE html>
<html lang="zh-Hant">
  <head>
    <meta charset="utf-8">
    <title>localStorage</title>
  </head>
  <body>
    <p>localStorage 測試</p>
    <script>
      // js 相關程式
    </script>
  </body>
</html>
<!DOCTYPE html>
<html lang="zh-Hant">
  <head>
    <meta charset="utf-8">
    <title>sessionStorage</title>
  </head>
  <body>
    <p>sessionStorage 測試</p>
    <script>
      // js 相關程式
    </script>
  </body>
</html>

無痕視窗

localStorage 在無痕視窗中,結束掉瀏覽器之後,也會將 localStorage 的資料清除,這本來就是無痕視窗的特性:不儲存任何使用者資料。

Last updated