Information stored in IndexedDB is not retained permanently

My journey to explore various web technologies (such as HTML, CSS, JavaScript) led me to create a simple web application. To enhance the functionality of my app, I integrated IndexedDB for data storage and operations like insert, update, get and delete.

However, a significant issue arises when I close or reload the browser tab - the database disappears along with all the stored data. Is there a method to retain this data even when the browser is closed?

The initialization of IndexedDB in the code snippet below:

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 function used to add 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);
            }
        });
    }
}

Database name and store details:

const nameOfDB = 'LocalDB';
const nameStorePersons = 'persons';

An illustration of the inserted data:

const persons = [
        {
            "id" : "d1",
            "filename" : "documents/d1.pdf",
            "status" : "Pending"
        },
        {
            "id" : "d2",
            "filename" : "documents/d2.pdf",
            "status" : "Testing"
        }]

Answer №1

The information stored in IndexedDB is associated with the specific combination of URL and port number. For instance, data saved for https://example.com will remain intact until the cached data is cleared. It's important to note that http://example.com is considered a different URL due to protocol differences. Furthermore, varying port numbers also distinguish URLs, such as http://localhost:8000 vs. http://localhost:8001. To retrieve data consistently across sessions when using IndexedDB, it is crucial that the same URL is used.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Node.js - Retrieving POST request parameters and directing users in an Express application

I encountered this specific issue while setting up a post endpoint for my nodejs CLI script that utilizes express to handle requests. app.use( express.static( path.format({dir: __dirname, base: 'client/dist'})) ); app.use( express ...

Refresh information periodically within a Node.js application

Recently, I developed a web application using nodejs to fetch data from Amazon. My goal is to have the app update at regular intervals for different purposes: - Every 15 minutes for real-time inventory monitoring - Once daily for less frequently changing d ...

Is it possible to switch from kilometers to miles on the distance matrix service in Google Maps?

let distanceService = new google.maps.DistanceMatrixService(); distanceService.getDistanceMatrix({ origins: [sourceLocation], destinations: [destinationLocation], travelMode: google.maps.TravelMode.DRIVING, unitSystem: google.maps.UnitSystem.IMPERI ...

'Mastering the implementation of promises in React context using TypeScript'

I've been diving into the world of incorporating TypeScript in React and I'm facing a challenge with implementing async functions on context. The error that's popping up reads as follows: Argument of type '{ userData: null; favoriteCoc ...

CSS - Help! Seeing different results on Internet Explorer

I'm currently handling an OSCommerce website, and I'm trying to figure out why this issue is occurring. You can view the website at this link: The layout looks completely different on Internet Explorer, and I'm puzzled as everything should ...

Verify whether the type of the emitted variable aligns with the specified custom type

Currently, I am in the process of testing Vue 3 components using jest. My main objective is to receive an emit when a button is clicked and then verify if the emitted object corresponds to a custom type that I have defined in a separate file. Below is an e ...

Create a copy of a div element once the value of a select element has

After modifying a select option, I'm attempting to replicate a div similar to the example shown in this link: http://jsfiddle.net/ranell/mN6nm/5/ However, instead of my expected lists, I am seeing [object]. Any suggestions on how to resolve this issue ...

Effortlessly showcase JSON data in an HTML owl carousel

Is there a way to display JSON data in HTML format? I have a JSON file containing reviews from Facebook, and I would like to showcase them on my website. Each review should be placed in its own div element. The JSON data below is extracted from the Faceboo ...

Choose a specific element using jQuery based on a class that is shared by several elements

I am looking to target an element with the class 'submenu-expand' and apply an additional class to it. $('.menu-item').on('click',function(){ $('.submenu-expand').toggleClass('expanded') }) While this cod ...

Welcome to the Kickme command in Discord.js!

I am attempting to create a command that enables any user to trigger the !kickme command, which will result in them being kicked from the server. Additionally, I want the command to send a direct message to the user who initiated it. However, I am facing ...

What is the purpose of utilizing "({ })" syntax in jQuery?

What is the purpose of using ({ }) in this context? Does it involve delegation? Can you explain the significance of utilizing this syntax? What elements are being encapsulated within it? For instance: $.ajaxSetup ({ // <-- HERE error: fError, ...

Personalizing the label of a select input using materialui

Working on customizing a select element using the "styled" method: const StyledSelect = styled(Select)` height: 2rem; color: #fff; border-color: #fff; & .${selectClasses.icon} { color: #fff; } & .${outlinedInputClasses.notchedOutl ...

Angular's ng-repeat allows you to iterate over a collection and

I have 4 different product categories that I want to display in 3 separate sections using AngularJS. Is there a way to repeat ng-repeat based on the product category? Take a look at my plnkr: http://plnkr.co/edit/XdB2tv03RvYLrUsXFRbw?p=preview var produc ...

Leverage the power of Angular CLI within your current project

I am currently working on a project and I have decided to utilize the angular cli generator. After installing it, I created the following .angular-cli file: { "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "project": { "name": " ...

How can Angular hide a global component when a particular route is accessed?

Is it possible to hide a global component in Angular when a specific route is opened? For instance, consider the following code: app.component.html <app-header></app-header> <app-banner></app-banner> <!-- Global Component I w ...

What is the process for creating a see-through background?

I'm not sure if this question has been asked before, so please forgive me and provide a link if it has. However, I haven't come across it on here yet. My aim is to create a transparent background that displays the wallpaper of the laptop's ...

Strategies for distributing a single lit-element instance among multiple web components

With numerous web components stored in individual repositories, I am seeking a way to share a single instance of lit-element/lit-html across all of them in order to optimize bundle size. Rather than having a separate instance in each bundle. To achieve th ...

Display information from dynamically generated pages using Gatsby JS sourcing data from CSV files

I've been working on creating pages in Gatsby JS from a csv file and everything seemed to be going smoothly. However, when it comes to displaying the data on these generated pages, I keep running into issues with undefined variables and can't see ...

Switching ng-show value from separate controller

I'm currently trying to update my ng-show variable whenever a state changes. In my default index.html file, the code looks like this: <div id="searchBar" ng-show="searchBar" ng-controller="mainController"></div> However, since this is no ...

Updating Vue.js Component Data

I have set up a basic Example Component which is bound to a Vue Instance as shown below: <template> <div class="container-fluid"> <div class="row"> <div class="col-md-8 col-md-offset-2"> < ...