IndexedDB Example
by Jagi
HTML
<div id="results"></div>
CSS
body {
font-family: sans-serif;
padding: 10px;
}
JavaScript
const customerData = [
{ idNumber: "19900101-4444", name: "Anders", age: 35 },
{ idNumber: "19791224-9999", name: "Sten", age: 32 }
];
const dbName = "the_name";
var request = indexedDB.open(dbName, 2);
request.onerror = function(event) {
// Handle errors.
};
request.onupgradeneeded = function(event) {
console.log("onupgradeneeded");
var db = event.target.result;
// Create an objectStore to hold information about our customers. We're
// going to use "ssn" as our key path because it's guaranteed to be
// unique - or at least that's what I was told during the kickoff meeting.
var objectStore = db.createObjectStore("students", { keyPath: "idNumber" });
// Create an index to search customers by name. We may have duplicates
// so we can't use a unique index.
objectStore.createIndex("name", "name", { unique: false });
// Use transaction oncomplete to make sure the objectStore creation is
// finished before adding data into it.
objectStore.transaction.oncomplete = function(event) {
// Store values in the newly created objectStore.
var customerObjectStore = db.transaction("students", "readwrite").objectStore("students");
for (var i in customerData) {
customerObjectStore.add(customerData[i]);
}
}
};