[html5]使用localStorage兼容低版本Safari無法使用indexeddb的情況


摘要

簡單場景描述:將html5開發的app內嵌入ios app中,有部分數據,需要在本地存儲,就想到使用瀏覽器的localstorage或者indexeddb,另外localstorage存儲的方式是key,value的方式,並且value是字符串類型的,一般會將json字符串的方式保存,但用起來不太方便,在使用的時候需要轉換為json對象。indexeddb存儲的是文檔類型,類似於mongodb的document。操作更方便。但對低版本的兼容性不太好。

解決辦法

http://git.oschina.net/wolfy/indexed-store-db

通過下面的代碼判斷當前瀏覽器是否支持indexed db

window.indexedDB = window.indexedDB ||
                   window.mozIndexedDB ||
                   window.webkitIndexedDB ||
                   window.msIndexedDB;
window.IDBTransaction = window.IDBTransaction ||
                   window.webkitIDBTransaction ||
                   window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange ||
                   window.webkitIDBKeyRange ||
                   window.msIDBKeyRange;
    var db = {
        version: 1, // important: only use whole numbers!
        isSupport: function () {// support indexeddb or not
            if (!window.indexedDB)
                return false;
            return true;
        },
        ......
      }

一個例子

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="js/index-store-db-1.0.js"></script>
    <script>

        var user1 = { id: 1, name: "wolfy", age: 20 };
        var user2 = { id: 2, name: "wolfy", age: 20 };
        //set local indexed db name
        app.db.objectStoreName = "app_test";
        //save data to indexed db
        app.db.save(user1, function () {
            console.log("Save success");
        });
        app.db.save(user2, function () {
            console.log("Save success");
        });
        //query user by id
        app.db.get(1, function (item) {
            console.log("query success", item);
        });
        //query all user
        app.db.getAll(function (items) {
            console.log("query all success", items);
        });
        
        app.db.delete(1, function () {
            console.log("delete success");
        });
    </script>
</head>
<body>

</body>
</html>

結果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM