Last active
June 8, 2016 13:32
-
-
Save leplatrem/9468f4785e872ec40a079f8e267a0a81 to your computer and use it in GitHub Desktop.
This file contains 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> | |
<head> | |
<meta charset="utf-8"> | |
<title>IDB demo</title> | |
</head> | |
<body> | |
<div id="results"></div> | |
<script> | |
function log(msg) { | |
document.getElementById("results").innerHTML += `<p>${msg}</p>`; | |
} | |
const STORE_NAME = "collection"; | |
const dbRequest = window.indexedDB.open("database", 1); | |
dbRequest.onerror = (event) => log(`An error occured ${event.target.error}`); | |
dbRequest.onblocked = (event) => log(`Blocked by other tab ${event.target.error}`); | |
dbRequest.onupgradeneeded = (event) => { | |
log("Database needs upgrade"); | |
event.target.result.createObjectStore(STORE_NAME, {keyPath: "id", autoIncrement: true}); | |
} | |
dbRequest.onsuccess = (event) => { | |
//if the request to open the database was successful, save the request objects result to the mydb variable | |
const db = event.target.result; | |
log("Database opened"); | |
const transaction = db.transaction([STORE_NAME], "readwrite"); | |
transaction.onerror = (event) => log(`Transaction error occured ${event.target.error}`); | |
transaction.onabort = (event) => log(`Transaction aborted.`); | |
transaction.oncomplete = (event) => log(`Transaction done.`); | |
const store = transaction.objectStore(STORE_NAME); | |
store.delete("haha").onsuccess = function (event) { | |
log("1"); | |
store.add({id: "haha"}).onsuccess = function (event) { | |
log("2"); | |
store.get("haha").onsuccess = function (event) { | |
log("3"); | |
store.put(Object.assign({}, event.target.result, {pi: 3.14})).onsuccess = function (event) { | |
log("4"); | |
store.get("haha").onsuccess = function (event) { | |
log("5"); | |
log(`Got ${JSON.stringify(event.target.result)}`); | |
log("6"); | |
store.add({id: "haha"}).onsuccess = () => {}; | |
} | |
} | |
} | |
} | |
} | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment