How access path in electron preloader script?

Viewed 250

In my electron app, I'm storing some settings data locally using the 'electron-json-storage' module.
However, in order to access this data, I must first find out the local path.
I'm using app.getPath('userData')); for this. You can see how my preloader script looks like below:

const { contextBridge, ipcRenderer, app } = require('electron');
let os = require("os");
contextBridge.exposeInMainWorld('electron', {
  ipcRenderer: {
    myPing() {
      ipcRenderer.send('ipc-example', 'ping');
    },
    on(channel, func) {
      const validChannels = ['ipc-example',];
      if (validChannels.includes(channel)) {
        ipcRenderer.on(channel, (event, ...args) => func(...args));
      }
    },
    once(channel, func) {
      const validChannels = ['ipc-example'];
      if (validChannels.includes(channel)) {
        ipcRenderer.once(channel, (event, ...args) => func(...args));
      }
    },
  },
  os:{
    cpuCount: os.cpus().length,
  },
  storage:{
    localPath: app.getPath('userData'),
  },
  
});

Unfortunately, it seems app isn't accessible in the preloader script because dev-tools shows the following error:

Uncaught Error: Cannot read property 'getPath' of undefined

Do I need to send the app path from a main script using a preloaded ipc-event, or is there any way to access it in the preloader itself?

Thanks!

1 Answers

The problem is that the app module is limited to the main process. As the preload scripts already run in the renderer, you cannot access app and would have to ask your main process via IPC for the path.

As a side note, it's probably preferable to just use IPC once (when your preload script is initialised, so before you define your main world functions) and cache the result the main process is returning.

Related