How to create a persistent on-disk session in ElectronJS?

Viewed 377

How do I create a session which is persistent with on-disk storage so that I can load it even after the app quits? The Session class has a storagePath property which returns an absolute file system path for the session if it persists on disk, but this property is read-only.

I can't seem to find a way to set this path, the API reference doesn't contain any helpful methods.

So how do I make my session persist on disk?

1 Answers

The Session class has a storagePath property which returns an absolute file system path for the session if it persists on disk, but this property is read-only.

I can't seem to find a way to set this path, the API reference doesn't contain any helpful methods.

So how do I make my session persist on disk?

It's not very intuitive, but the ses.fromPartition API docs state:

If partition starts with persist:, the page will use a persistent session available to all pages in the app with the same partition. if there is no persist: prefix, the page will use an in-memory session. If the partition is empty then default session of the app will be returned.

For example:

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

const ses = session.fromPartition('persist:my-partition');
console.log(ses.isPersistent()) // true 
console.log(ses.getStoragePath()) // /Users/user/Library/Application Support/app/Partitions/my-partition (on macOS)

Then the session partition path should be /USERDATA/Partitions/my-partition, where USERDATA is the value of app.getPath('userData').

Related