Skip to content

Instantly share code, notes, and snippets.

@mvark
Created February 2, 2025 17:30
Show Gist options
  • Save mvark/b07fcb6289b9cd84efb3a467d7b4f9ef to your computer and use it in GitHub Desktop.
Save mvark/b07fcb6289b9cd84efb3a467d7b4f9ef to your computer and use it in GitHub Desktop.
A Simple IndexedDB Example. Use "Application" tab of browser Developer Tools to view & manage contents of IndexedDB databases.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>IndexedDB Example</title>
</head>
<body>
<h1>IndexedDB Example</h1>
<form id="dataForm">
<label for="dataInput">Enter Data:</label>
<input type="text" id="dataInput" required>
<button type="submit">Add Data</button>
</form>
<button id="getData">Get Data</button>
<pre id="output"></pre>
<script>
let db;
const request = indexedDB.open('myDatabase', 1);
request.onupgradeneeded = function(event) {
db = event.target.result;
const objectStore = db.createObjectStore('myObjectStore', { autoIncrement: true });
};
request.onsuccess = function(event) {
db = event.target.result;
// Add Data
document.getElementById('dataForm').addEventListener('submit', function(event) {
event.preventDefault();
const dataInput = document.getElementById('dataInput').value;
const transaction = db.transaction(['myObjectStore'], 'readwrite');
const objectStore = transaction.objectStore('myObjectStore');
objectStore.add({ value: dataInput });
transaction.oncomplete = function() {
console.log('Data added successfully');
document.getElementById('dataForm').reset();
};
transaction.onerror = function(event) {
console.error('Transaction error:', event.target.errorCode);
};
});
// Get Data
document.getElementById('getData').addEventListener('click', function() {
const transaction = db.transaction(['myObjectStore'], 'readonly');
const objectStore = transaction.objectStore('myObjectStore');
const request = objectStore.getAll();
request.onsuccess = function(event) {
const output = document.getElementById('output');
output.textContent = JSON.stringify(event.target.result, null, 2);
};
request.onerror = function(event) {
console.error('Request error:', event.target.errorCode);
};
});
};
request.onerror = function(event) {
console.error('Database error:', event.target.errorCode);
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment