> For the complete documentation index, see [llms.txt](https://docs.webmix.cc/html5/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.webmix.cc/html5/5.-web-storage/5.1-localstorage-yu-sessionstorage.md).

# 4.1 localStorage 與 sessionStorage 簡介

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

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

## cookie 與 localStorage 與 sessionStorage 比較

| 特性   | cookie                  | localStorage    | sessionStorage |
| ---- | ----------------------- | --------------- | -------------- |
| 生命週期 | 預設是關閉瀏覽器後失效，但可以設定失效的時間。 | 除非手動清除，否則並不會消失。 | 關閉頁面或瀏覽器後失效。   |
| 大小   | 大約4K                    | 一般是 5Mb         | 一般是 5Mb        |

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

範例：

{% embed url="<https://youtu.be/ooKBwjBn_yM>" %}

## Web Storage

在 `html5` 資料夾底下，建立 `web_storage` 資料夾，然後在這個資料夾底下，建立 **`localstorage.html`**、**`sessionstorage.html`** 內容如下，以便觀察測試。

{% tabs %}
{% tab title="localstorage.html" %}

```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>
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="sessionstorage.html" %}

```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>
```

{% endtab %}
{% endtabs %}
