IndexedDB is a substantial data repository embedded in the browser that allows for persistent data storage through key-value pairs. It supports storing various JavaScript data types like boolean, number, string, undefined, null, date, regular expression, object, array, binary large object (blob), and files.
An important entity stored within web browsers is known as IndexedDB, where data is stored using key-value pairs. This storage mechanism allows for the storage of various types of data, ranging from simple to intricate, as the stored values.
Why is indexedDB used?
- You can build web apps with IndexedDB that function both online and offline.
- Applications that need to store a lot of data but don't require a constant internet connection can benefit from it.
- As an illustration, Google Docs uses IndexedDB to maintain the cached content in the browser and periodically synchronizes with the server. This improves user experiences while enabling Google Docs to perform better.
- Additionally, you can discover various programmes like online notepads, code sandboxes, tests, to-do lists, and CMS that primarily utilize IndexedDB.
IndexedDB architecture
The illustration below displays the structure of IndexedDB:
Databases
At the highest level of IndexedDB, there exists a database that contains one or more object stores.
In IndexedDB, it is possible to have either a single or multiple databases. Typically, in a web application, you would create a single database.
Object Stores for datas
Object storage can serve as a container to efficiently manage both data and associated indexes. Its functionality mirrors that of SQL databases.
Data stored in a structured format where each record consists of a key and a corresponding value is stored in object storage.
Indexes
Indexes enable the searching of data based on the properties of an object. Technically, indexes are constructed on object stores referred to as parent object stores.
For example, in the case of storing contact details, it would be beneficial to create indexes for the email address, complete name, and physical address. This enables efficient searching based on these specific criteria.
Principles of IndexedDB
Below are concise explanations of the core principles of IndexedDB:
1) IndexedDB databases keep key-value pairs.
IndexedDB allows for storing complex data structures such as objects and blobs, in contrast to the simpler key-value pairs supported by localStorage and sessionStorage.
Keys can also be represented as binary entities or as the attributes of these entities.
Indexes for efficient searching and sorting can be generated using any attribute of the objects.
2) IndexedDB supports transactions
A transaction is always involved when data is being read from or written to an IndexedDB database.
When users open a web application in multiple tabs or windows simultaneously and both read from and write to the database, they benefit from the transactional model. This model ensures data integrity by safeguarding the process of interacting with the database.
3) The IndexedDB API is primarily asynchronous.
IndexedDB utilizes asynchronous operations, where upon completion of a task and availability of the result, it informs you through DOM events.
4) The NoSQL system IndexedDB
IndexedDB makes use of NoSQL technology, which means it does not rely on SQL for querying data.
It utilizes the query that returns a cursor instead. Subsequently, you can navigate through the outcome set by using the pointer.
5) IndexedDB adheres to the same-origin rule
An origin is the URL of the page that contains the protocol, domain, and port where the code is executed.
- domain: logic-practice.com
- protocol: https
- port: 443
IndexedDB adheres to the same-origin policy, which means that each origin is associated with its own distinct set of databases. Moreover, databases from disparate sources cannot be accessed by a single origin.
Develop the project structure in steps.
- First, make an indexeddb folder in a new folder. Make a new subfolder called js inside the indexeddb folder.
- Second, Create javascript in the js folder and the html file in the indexeddb folder.
- Third, insert the <script> tag in the index.html file to link to the app.js file or use the <script> tag for the javascript code.
Filename: Demo.html
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<meta name = "viewport" content = "width=device-width, initial-scale = 1.0">
<title> JavaScript IndexedDB </title>
</head>
<body>
<script src = "https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image"> </script>
Or
<script> //javascript indexedDB code </script>
</body>
</html>
Fundamental IndexedDB operations
The following provides an overview of the fundamental operations of IndexedDB databases, including.
- Establishing a database connection
- Adding something to the object storage.
- Taking information out of the object store.
- Iterating through a set of results using a cursor.
- Removing a piece of data from the object database.
Prior to establishing a connection in the IndexedDB database, it is essential to set up the project structure.
The outlined procedures are applicable for performing operations and configuring indexedDB.
1) Verify whether the IndexedDB is supported.
The following code snippet is used to check if a web browser supports the IndexedDB feature. This check may be unnecessary now as most modern web browsers already have built-in support for IndexedDB.
if (!window.indexedDB) {
console.log(` Your browser does not accept IndexedDB`);
return;
}
2) Open the database
The open function in the web browser is employed to establish a connection with a database.
const request_variable = indexedDB.open('tutorial_data', 1);
The open function accepts two parameters.
The first parameter, 'tutorial_data', represents the name of the indexedDB database.
The second parameter, 1, signifies the version of the indexedDB database.
The open function of the IDBOpenDBRequest interface accepts a request object that must be an instance of the same interface.
Upon calling, an object referred to as openRequest is generated, and it is essential to monitor events related to it. When the operation is successful, a message indicating that the database is ready is shown. The openRequest.result contains the "database object," which should be utilized for future calls.
request_variable.onerror = function(event) {
console.log(" The function shows error! ");
};
- Error: failing to open error.
- The onupgradeneeded event can be raised when you first open the database.
- The onupgradeneeded event also occurs if the database is opened on a second attempt with a version that is higher than the current version.
- The "onupgradeneeded event handler" can be used to initialize the object storage and indexes for the initial time.
- For instance, the Contacts object store and its index are created by the following onupgradeneeded event handler.
request_variable.onsuccess = function(event) {
console.log(" The function shows success! ");
};
3) Establish object stores
// create the names object store and indexes
request.onupgradeneeded = (event) => {
let db_variable = event.target.result;
// create the Name object store
// with auto-increment id
let store_varible = db_variable.createObjectStore('Rank', {
autoIncrement: true
});
// create an index on the rank property
let index = store_varible.createIndex('name', ' name', {
unique: true
});
};
How it functions
Retrieve the IDBDatabase object initially and assign it to the db_variable using the event.target.result.
The auto-increment id
To create a Name object storage with an auto-increment key, you can achieve this by invoking the createObjectStore function for the second time.
For each new object entered into the Name object store, the IndexedDB_VARIABLE can create an auto-increment number as the key, starting at one.
- To establish an index on the rank property, execute the createIndex method third.
- Since each rank is distinct, so too should the index.
- You achieve this by passing the createIndex method's third argument, (unique: true).
4) Use insert, read, and delete data using the object store
Users have the ability to manipulate database information by utilizing the JavaScript function and the indexedDB method for tasks like insertion, retrieval, and deletion.
Examples
Displayed below are demonstrations of the IndexedDb operation, functions, and results. These examples illustrate the fundamental operations and their execution process through various scenarios.
Example 1
The example demonstrates the use of a JavaScript function to determine browser support for IndexedDB.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv = "Content-Type" content = "text/html; charset = utf-8" />
<title> JavaScript IndexedDb Demo </title>
</head>
<body>
<h2> JavaScript IndexedDb Demo </h2>
<p id = "demos"> </p>
</body>
<script>
if (!window.indexedDB) {
console.log("The browser does not support IndexedDB");
alert("Your browser does not support IndexedDB");
document.getElementById("demos").innerHTML = "Your browser does not support IndexedDB";
}else{
console.log("Your browser support IndexedDB");
alert("Your browser support IndexedDB");
document.getElementById("demos").innerHTML = "Your browser support IndexedDB";
}
</script>
</html>
Output
The displayed image illustrates the outcome of integrating IndexedDB into web browsers.
Example 2
The illustration demonstrates how web browsers endorse IndexedDB using a JavaScript event. This event triggers functions for handling errors, successes, or upgrades. When the database functions properly and manages data effectively, the success function executes within the JavaScript-IndexedDB.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv = "Content-Type" content = "text/html; charset = utf-8" />
<title> JavaScript IndexedDb Demo </title>
</head>
<body>
<h2> JavaScript IndexedDb Demo </h2>
<p id = "demos"> </p>
<p id = "demo2"> </p>
</body>
<script>
if (!window.indexedDB) {
document.getElementById("demos").innerHTML = "Your browser does not support IndexedDB";
}else{
document.getElementById("demos").innerHTML = "Your browser support IndexedDB";
}
var request_variable = window.indexedDB.open("newData", 1);
request_variable.onerror = function(event) {
console.log(" The function shows error! ");
document.getElementById("demo2").innerHTML = "The function shows error!";
};
request_variable.onsuccess = function(event) {
console.log(" The function shows success! ");
document.getElementById("demo2").innerHTML = "The function shows success!";
};
request_variable.onupgradeneeded = function(event) {
console.log(" The function shows upgraded! ");
}
</script>
</html>
Output
The displayed image illustrates the event that triggered the use of IndexedDB in web browsers.
Example 3
The following example demonstrates how browsers provide support for IndexedDB using a JavaScript event. In this scenario, an error function is executed upon encountering any errors. Whenever an error occurs within the IndexedDB, including during availability checks and other operations, the onerror function in JavaScript is triggered.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv = "Content-Type" content = "text/html; charset = utf-8" />
<title> JavaScript IndexedDb Demo </title>
</head>
<body>
<h2> JavaScript IndexedDb Demo </h2>
<p id = "demos"> </p>
<p id = "demo2"> </p>
<p id = "demo3"> </p>
</body>
<script>
if (!window.indexedDB) {
document.getElementById("demos").innerHTML = "Your browser does not support IndexedDB";
}else{
document.getElementById("demos").innerHTML = "Your browser support IndexedDB";
}
var request_variable = window.indexedDB.open("newData", 1);
request_variable.onerror = function(event) {
console.log(" The function shows error! ");
document.getElementById("demo2").innerHTML = "The function shows error!";
};
request_variable.onsuccess = function(event) {
console.log(" The function shows success! ");
document.getElementById("demo2").innerHTML = "The function shows success!"+request_variable;
};
</script>
</html>
Output
The displayed image depicts an error notification originating from IndexedDB and being presented to web browsers.
Example 4
The demonstration illustrates how web browsers endorse the usage of IndexedDB through a JavaScript event. This event triggers a function that handles upgrades following a database version update. When transitioning from database version 1 to version 2, the onupgradeneeded function is invoked.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv = "Content-Type" content = "text/html; charset = utf-8" />
<title> JavaScript IndexedDb Demo </title>
</head>
<body>
<h2> JavaScript IndexedDb Demo </h2>
<p id = "demos"> </p>
<p id = "demo2"> </p>
<p id = "demo3"> </p>
</body>
<script>
if (!window.indexedDB) {
document.getElementById("demos").innerHTML = "Your browser does not support IndexedDB";
}else{
document.getElementById("demos").innerHTML = "Your browser support IndexedDB";
}
//the database name with the second version
var request_variable = window.indexedDB.open("newData2", 2);
request_variable.onerror = function(event) {
console.log(" The function shows error! ");
document.getElementById("demo2").innerHTML = "The function shows error!";
};
//the transaction of the database successfully
request_variable.onsuccess = function(event) {
console.log(" The function shows success! ");
document.getElementById("demo2").innerHTML = "The function shows success!"+request_variable;
};
//the indexedDB database upgrade with the version
request_variable.onupgradeneeded = function(event) {
console.log(" The function shows upgraded! ");
document.getElementById("demo3").innerHTML = "The function shows upgraded!";
}
</script>
</html>
Output
The displayed image illustrates an enhanced message within the IndexedDB for web browsers.
Example 5
The demonstration illustrates how browsers provide support for IndexedDB through a JavaScript event. This function is utilized to create an object for managing data within the database, setting up auto-increment and unique data variables.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv = "Content-Type" content = "text/html; charset = utf-8" />
<title> JavaScript IndexedDb Demo </title>
</head>
<body>
<h2> JavaScript IndexedDb Demo </h2>
<p id = "demos"> </p>
<p id = "demo2"> </p>
</body>
<script>
const request = indexedDB.open('DB_name', 1);
// create the Names object store and indexes
request.onupgradeneeded = (event) => {
let db_variable = event.target.result;
// create the Names object store
// with auto-increment id
let store_variable = db_variable.createObjectStore('Names', {
autoIncrement: true
});
// create an index on the email property,
let index_data = store_variable.createIndex('email', 'email', {
unique: true
});
};
function insertContact(db_variable, name) {
// create a new transaction for the database
const text_data = db_variable.transaction('Names', 'readwrite');
// get the Names object store_variable
const store_variable = text_data.objectStore('Names');
let db_que = store_variable.put(name);
// handle success of the transaction
db_que.onsuccess = function (event) {
console.log(event);
};
// handle the error of the transaction
db_que.onerror = function (event) {
console.log(event.target.errorCode);
}
// close the database when the transaction completes
text_data.oncomplete = function () {
db_variable.close();
};
}
request.onsuccess = (event) => {
const db_variable = event.target.result;
const db_variable1 = event.target;
const db_variable2 = event.type;
console.log("create object and store data " +db_variable);
console.log("create object and get target " +db_variable1);
console.log("create type object "+ db_variable2);
};
</script>
</html>
Output
The displayed image illustrates the event that triggered the use of IndexedDB in web browsers.
Summary
IndexedDB comprises databases with object storage in each of them. Normally, a single IndexedDB database is generated for every web application.
IndexedDB is particularly advantageous for web applications that can function both online and offline without requiring a continuous internet connection. This feature is particularly beneficial for such applications.