[HTML5] 整理幾種方法儲存資料在Client用戶端 包含IndexedDB快速上手Sample Code

HTML5 store data in client side

在恆逸的上課隨手筆記,上課節奏很快,細節無法詳細說明Q_Q

 

整理一下截至2019-10-31為止,將資料儲存在瀏覽器用戶端的幾種實現方法

1.cookie:現在資安抓很嚴,都會要求網站啟用httpOnlyCookie,只允許Server端網站存取Cookie,所以不建議再透過Javascript存取cookie

2.Web Storage(包含sessionStorage、localStorage):只能儲存字串,請見我另一篇文章 [Html 5] WebStorage - localStorage和sessionStorage 基本使用方法

3.Web SQL:被棄用了(原因貌似和SQL Lite綁很緊,不是個很好的規格標準),完全不考慮使用

3.Application Cache:專門快取靜態資源(.html、.js、.css、圖片) 由於必須頻繁地維護.manifest檔來控制Cache 而且不適合使用很多頁面的網站

還有一些缺點:Application Cache 就是个坑| Zoom's Blog(中文翻譯)

Application Cache is a Douchebag by Jake ArchibaldMay 08, 2012 (英文原版)

所以已被棄用並從HTML標準規格中移除,請完全不考慮使用:https://html.spec.whatwg.org/multipage/offline.html#offline

如果要開發Offline Web applications (離線Web應用程式),建議改用 Service Worker  

不過由於Service Worker 目前規格還在制定中,這段期間空窗期很尷尬

如果你的專案經理、老闆還傻傻地答應客戶要開發「離線Web應用程式」,請回答他目前Web技術還不成熟,硬幹會有許多Bug(原因請見上述連結)、恐會造成專案驗收不了、公司被罰錢.....等等XD

4:Indexed Database API(或稱IndexedDB):相比Web Storage,它可以儲存Javascript Object

以下是 IndexedDB的新增、刪除、修改、查詢Sample Code

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script>
        var db;
        var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
        var IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction;

        var req = indexedDB.open("mydb");

        req.onsuccess = function (e) {
            console.log("open");
            db = e.target.result;
        };

        req.onerror = function () {
            console.log("error");
        };

        req.onupgradeneeded = function (e) {
            console.log("upgradeneeded");          

            var db = e.target.result;
            var emp = { id: 1, name: "ray" };
            var store = db.createObjectStore("employees", { keyPath: "id" });

            store.add(emp);
        }

        function addObj() {
            var txn = db.transaction("employees", "readwrite");
            var store = txn.objectStore("employees");

            var emp2 = { id: 2, name: "vivid" };

            var req = store.add(emp2);
            req.onsuccess = function (e) {
                console.log("add");
            }

            req.onerror = function () {
                console.log("error");
            };
        }

        function getObj() {
            var txn = db.transaction("employees", "readwrite");
            var store = txn.objectStore("employees");

            var req = store.get(2);

            req.onsuccess = function (e) {
                console.log("get");

                var emp = e.target.result;
                document.getElementById("result").innerHTML =
                    emp.id + ", " + emp.name;
            }

            req.onerror = function () {
                console.log("error");
            };
        }

        function deleteObj() {
            var txn = db.transaction("employees", "readwrite");
            var store = txn.objectStore("employees");

            var req = store.delete(1);

            req.onsuccess = function (e) {
                console.log("delete");
            }

            req.onerror = function () {
                console.log("error");
            };
        }

        function updateObj() {
            var txn = db.transaction("employees", "readwrite");
            var store = txn.objectStore("employees");

            var emp2 = { id: 2, name: "kevin" };

            var req = store.put(emp2);
            req.onsuccess = function (e) {
                console.log("put");
            }

            req.onerror = function () {
                console.log("error");
            };
        }


    </script>
</head>
<body>
    <input id="btnAdd" type="button" value="add" onclick="addObj()" />
    <input id="btnGet" type="button" value="get" onclick="getObj();" />
    <input id="btnDelete" type="button" value="delete" onclick="deleteObj()" />
    <input id="btnUpdate" type="button" value="update" onclick="updateObj()" />

    <hr />
    <div id="result"></div>
</body>
</html>

IndexedDB MDN說明文件:https://developer.mozilla.org/zh-TW/docs/Web/API/IndexedDB_API

至於它的生命周期,何時消失被清除,有空我再來研究一下Orz