-
-
Save suhailvs/b5f858debccbd6795524a0df61bd19a2 to your computer and use it in GitHub Desktop.
Very Simple IndexedDB Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8" /> | |
<title>IndexedDB</title> | |
</head> | |
<body> | |
<!-- https://www.codeproject.com/Articles/325135/Getting-Started-with-IndexedDB --> | |
<output id="printOutput"></output> | |
<script type="text/javascript"> | |
// This works on all devices/browsers, and uses IndexedDBShim as a final fallback | |
var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB; | |
// Open (or create) the database | |
var open = indexedDB.open("MyDatabase", 1); | |
// Create the schema | |
open.onupgradeneeded = function() { | |
var db = open.result; | |
var store = db.createObjectStore("MyObjectStore", {keyPath: "id"}); | |
}; | |
open.onsuccess = function() { | |
// Start a new transaction | |
var db = open.result; | |
var tx = db.transaction("MyObjectStore", "readwrite"); | |
var store = tx.objectStore("MyObjectStore"); | |
// Add some data | |
store.put({id: 12345, name: {first: "John", last: "Doe"}, age: 42}); | |
store.put({id: 67890, name: {first: "Bob", last: "Smith"}, age: 35}); | |
var output = document.getElementById("printOutput"); | |
output.textContent = ""; | |
store.openCursor().onsuccess = function(event) { | |
var cursor = event.target.result; | |
if (cursor) { | |
output.textContent += "id: " +cursor.key + " is " + cursor.value.name.first +", "; | |
cursor.continue(); | |
} | |
}; | |
// Close the db when the transaction is done | |
tx.oncomplete = function() { | |
db.close(); | |
}; | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment