简单场景描述:将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>
结果

[html5]使用localStorage兼容低版本Safari无法使用indexeddb的情况
原文:http://www.cnblogs.com/wolf-sun/p/6567607.html