< JavaScript

JavaScript - IndexedDB

Szerző: Sallai András

Copyright © 2025, Sallai András

Licenc: CC Attribution-Share Alike 4.0 International

Web: https://szit.hu

Minta

<div> <div class="input"> <label for="name">Név</label> <input type="text" id="name"> </div> <div class="input"> <label for="age">Kor</label> <input type="text" id="age"> </div> </div>
const addButton = document.getElementById("addButton"); const readButton = document.getElementById("readButton"); const nameInput = document.getElementById("name"); const ageInput = document.getElementById("age"); const request = indexedDB.open("test", 1); let db; request.onupgradeneeded = function (event) { const db = event.target.result; db.createObjectStore("users", { autoIncrement: true }); }; request.onsuccess = function (event) { db = event.target.result; console.log("Database opened successfully"); } addButton.addEventListener("click", () => { console.log('Hozzáadás...') if(!db) { console.log('Nincs adatbázis') return; } const transaction = db.transaction("users", "readwrite"); const store = transaction.objectStore("users"); store.add({ name: nameInput.value, age: ageInput.value }); }); readButton.addEventListener("click", () => { const transaction2 = db.transaction("users", "readonly"); const store2 = transaction2.objectStore("users"); const cursor = store2.openCursor(); cursor.onsuccess = function (event) { const result = event.target.result; if (result) { console.log( "Name:", result.value.name, "Age:", result.value.age ); result.continue(); } }; });