Reputation: 97
I created a small web application to learn different web technologies (HTML, CSS, JavaScript, etc.). Since, I would like to store data and perform some operations on it, I made use of IndexedDB. I am able to create a database and even perform insert, update, get & delete operations on it.
The issue remains when I close the browser and/or reload the page. I notice that the database doesn't exist anymore and all my data are lost.
Is there any way to "persist" the data, such that it won't be lost when the browser or the tab is closed ?
The creation of the IndexedDB is done as such:
let db = null;
function create_db(nameDB, stores) {
const request = window.indexedDB.open(nameDB, 1);
request.onerror = function(event) {
console.log("Problem opening DB.")
}
request.onupgradeneeded = function(event) {
db = event.target.result;
const store = db.createObjectStore(stores, {keyPath: 'id'});
store.transaction.oncomplete = function(event) {
console.log("Persons store successfully completed;")
}
}
request.onsuccess = function(event) {
db = event.target.result;
console.log("Successfully opened DB.")
insert_record(nameStorePersons, persons);
}
}
Edit:
The code used to insert records:
function insert_record(nameStore, records) {
if (db) {
const insert_transaction = db.transaction(nameStore, 'readwrite');
const store = insert_transaction.objectStore(nameStore);
insert_transaction.onerror = function () {
console.log("Problem with transactions.");
}
insert_transaction.oncomplete = function () {
console.log("All transactions complete.");
}
records.forEach(record => {
let request = store.add(record);
request.onerror = function(event) {
console.log("Could not add: ", record);
}
request.onsuccess = function(event) {
console.log("Successfully added: ", record);
}
});
}
}
The name of the database and store:
const nameOfDB = 'LocalDB';
const nameStorePersons = 'persons';
Example of the data that is inserted:
const persons = [
{
"id" : "d1",
"filename" : "documents/d1.pdf",
"status" : "Pending"
},
{
"id" : "d2",
"filename" : "documents/d2.pdf",
"status" : "Testing"
}]
Upvotes: 1
Views: 1178
Reputation: 41
With Edge it seems that persistent indexeddb
is not possible. In the developer tools, Application/IndexedDB
is shown as not persisted, and I don't see how this can be changed. On Chrome
, open chrome://settings/content/siteData
and either allow all web sites or just yours. And you need a secure context, as so often.
Upvotes: 0
Reputation: 1
The data that is stored in the IndexedDB is stored by URL + port number. So if the site is https://example.com the data will be persisted (until cleared by clearing the cached data) for that particular web URL. http://example.com is not the same URL. It also uses the port number. So http://localhost:8000 is not the same as http://localhost:8001. So if you are going to use the IndexedDB the URL being used must be the same to retrieve the data between sessions.
Upvotes: -1