-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIndexedDBExample03.htm
executable file
·88 lines (80 loc) · 3.15 KB
/
IndexedDBExample03.htm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<!DOCTYPE html>
<html>
<head>
<title>IndexedDB Example</title>
</head>
<body>
<p>This example works in Firefox 4+ and Chrome. Note that Firefox does not allow local files to access <code>indexedDB</code>, so you'll need to run this example through a web server to get it to work on Firefox (Chrome does not have this restriction).</code></p>
<p>Open up the console to see the results.</p>
<script>
(function(){
var indexedDB = window.indexedDB || window.msIndexedDB || window.mozIndexedDB || window.webkitIndexedDB,
IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction,
request,
store,
database,
users = [
{
username: "007",
firstName: "James",
lastName: "Bond",
password: "foo"
},
{
username: "ace",
firstName: "John",
lastName: "Smith",
password: "bar"
},
{
username: "foobar",
firstName: "Michael",
lastName: "Johnson",
password: "secret"
}
];
request = indexedDB.open("example");
request.onerror = function(event){
alert("Something bad happened while trying to open: " + event.target.errorCode);
};
request.onsuccess = function(event){
database = event.target.result;
initializeDatabase();
};
function initializeDatabase(){
if (database.version != "1.0"){
request = database.setVersion("1.0");
request.onerror = function(event){
alert("Something bad happened while trying to set version: " + event.target.errorCode);
};
request.onsuccess = function(event){
store = database.createObjectStore("users", { keyPath: "username" });
users.forEach(function(user){
store.add(user);
});
outputValues();
};
} else {
outputValues();
}
}
function outputValues(){
var store = database.transaction("users").objectStore("users"),
request = store.openCursor();
request.onsuccess = function(event){
var cursor = event.target.result;
if (cursor){ //always check
console.log("Key: " + cursor.key + ", Value: " + JSON.stringify(cursor.value));
cursor.continue(); //go to the next one
} else {
console.log("Done!");
}
};
request.onfailure = function(event){
console.error("Iteration did not succeed.");
};
}
})();
</script>
</body>
</html>