Open In App

Persisting Data in ElectronJS

ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime.

All complex web applications make use of Local Storage. Local Storage (a.k.a DOM Storage) is a type of web storage that allows websites to store, persist and access this data within the client-side browser without any expiration date. The data that persisted in the local storage will still be accessible even after the browser window is closed or reloaded. The application data is stored locally in the client-side browser. HTML5 and Vanilla JavaScript provide extensive support for localstorage via APIs. Before local storage was implemented, the data used to be stored in cookies which were included in every HTTP REST API call to the server. Web local storage is more secure than cookies, and we can store large amounts of data (up to 5 MB) without affecting the performance of the website. This data is never transferred to the server and will remain in the client-side browser until the local storage is not cleared manually. Local Storage is implemented per origin basis i.e. based on the domain and the protocol of the website. All webpages from the same origin have access to the same data within the local storage. The same webpage accessed from different Protocols such as HTTP or HTTPS has a different local storage instance created for them. Any data stored in the local storage when the webpage is in Private or Incognito mode will be cleared once all Incognito tabs are closed. The local storage is not to be confused with Session Storage in which the data is persisted until the page session ends. Once the session is terminated, the data is erased. All modern browsers support Local Storage including Chromium. 



Even though Chromium supports Local Storage, Electron does not provide us with a built-in way to store and persist user settings and other data within the local storage. However, with the help of external npm packages, we can persist and access data within an Electron application simply and efficiently. In this tutorial, we will implement local storage in Electron by using the electron-settings npm package. For more detailed information, refer to the link: https://www.npmjs.com/package/electron-settings. This package has been adopted and is used by Electron itself for demo purposes.  We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system.



Example: Follow the Steps given in Dynamic Styling in ElectronJS to set up the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. We will continue building our application using the same code base. Additionally, install the electron-settings package using npm. According to the official documentation, this package is a simple and robust settings management library for Electron applications. This package allows us to persist user data and settings within the application between reloads and application startups just like local storage. All the data persisted using this package is stored in a JSON file by the name of settings.json located in the user’s local system application directory. Refer to the code for a better understanding. 

npm install electron-settings --save

Also, perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. The basic steps required to set up the Electron application remain the same. 
package.json: 

{
    "name": "electron-persist",
        "version": "1.0.0",
            "description": "Persist Data in Electron ",
                "main": "main.js",
                    "scripts": {
        "start": "electron ."
    },
    "keywords": [
        "electron"
    ],
        "author": "Radhesh Khanna",
            "license": "ISC",
                "dependencies": {
        "electron": "^8.3.0",
            "electron-settings": "^4.0.2"
    }
}

Output: 

Persisting Data in Electron: The electron-settings npm package can be directly used in the Main Process and the Renderer Processes of the application for accessing the storage. This package is designed and works similarly as compared to the Window.localStorage Web API. This package is compliant and works without any errors as of Electron v8.3.0 and it is regularly updated. We will now implement this package in the Electron application. For more detailed information on this package, version updates, and changelogs, refer to the link: https://electron-settings.js.org/.




<h3>Persist Data and User Settings in Electron</h3>
<h5>Enter Sample Text here</h5>
<input type="text" id="sample">
<button id="submit">
    Submitting the Data
</button>




const electron = require('electron')
const settings = require('electron-settings');
 
console.log('File used for Persisting Data - ' +
    settings.file());
 
let sample = document.getElementById('sample');
let submit = document.getElementById('submit');
 
settings.get('key.data').then(value => {
    console.log('Persisted Value - ' + value);
})
 
settings.has('key1.data').then(bool => {
    console.log('Checking if key1.data Exists - ' + bool)
});
 
submit.addEventListener('click', () => {
    console.log('Sample Text Entered - ' + sample.value);
    console.log('Persisting Data in electron-settings');
 
    settings.set('key', {
        data: sample.value
    });
});

Explanation: In the above application, we are inputting sample text data from the user using the HTML DOM Input Element. We are then persisting and accessing this data in the Electron application using the Instance methods of the electron-setting package. The electron-settings npm package supports the following Instance methods which have also been used in the above code. 

Note: The key parameter is an Optional parameter. If the key parameter is not passed, it will reset all the data persisted in the application using the electron-settings package.

Output: At this point, upon launching the Electron application, we should be able to persist data entered by the user within the application and successfully retrieve it when the application is reloaded or relaunched. 


Article Tags :