Electron persist data with context isolation

210 Views Asked by At

I'm new to Electron and searching for a good way to persist user data. As I understood it you should not expose NodeJs functionality into the renderer processes because of the security implication of context isolation.

So what is the best practise for implementing a shared local data storage that I can use between the renderer and the (background) main process? Only the main process has access to the file system via the node api, so would I always have to interact with my storage from the renderer by calling a dependency exposed in the preload script?

Ideally I would like to have something like chrome.storage for extensions that I can use in both processes, but not sure if this is possible. Any input is appreciated!

1

There are 1 best solutions below

0
exception On

The solution would really depend on the type of data you wish to persist...

If they are just settings for your program, you can use something like electron-settings package

const settings = require('electron-settings');

But, the information is stored in a plain text JSON file in the associated AppData folder.

Then use IPC channel

const { ipcMain } = require('electron');

ipcMain.handle('myInvocationName', () => {
        return some_data;
});

for communication from the main process to your renderer process.

Conversely, your renderer process can request information from the main process using

const { ipcRenderer } = require('electron');

ipcRenderer.invoke('myInvocationName').then((returned_data) => {
    // do something with returned_data
});