Save data offline with IndexDB

Tram Ho

Hello everyone, in the previous two articles, I introduced the service worker, workbox and how to help you cache resources in the web to be able to run the website even when there is no network. At this failure, I will show you how to save data while in offline mode with indexDB

What is IndexDB

IndexDB is an archive under the user’s browser (like localStorage). The data in indexDB will be saved as key – value. The concept is quite simple, isn’t it, let’s get started on the main thing right now


Please clone this project to you: . If you open the main.js file, you will find yourself checking to see if your browser supports indexDb, but it will probably support it, because indexDB now running can almost run on all browsers.

To be able to run the other demo, you need to install http-server

Then cd into the project directory and run

Create connection

First to create a connection, you can do the following

Where products is the connection name, 1 is the version. F5 again, go to the Application section in inspect will see 1 item is IndexedDB

So we have opened a successful connection

Create an object to store (object stores)

Now that the connection has been created, we will create one more object to store data related to furniture. Update the code above a bit

You will see the version is now up to 2, why is that? This is to ensure the integrity of the object stores and indexes data will only be created during the database upgrade process. This means they will be created in the upgrade callback function in . This callback will only run when the version (currently 2) is larger than the current version on the browser or the db does not exist. And you will also see that in each case there is no break, this is to ensure that all cases after the first case is run will be executed.

More data

Now I will add some data to it

And now press the button to add Products and check again 😄


Now try the search function. First we have to create a few more indexes to search by.

Now let’s add these functions

Writing this way is just a demo, so it’s a bit bad, because it will only search correctly according to the full name saved. 😦 If I have time, I will update later

With 3 articles on this offline hope to help you a lot. Thank you for your interest in my article

Share the news now

Source : Viblo