javascriptelectronfile-management

Opening files/folders using Electron and ContextIsolation


I have been trying to build an app for file managing and different stuff for work. One of the feautures is to open links in windows file explorer, but I am not able to do it. These are the files isolated from the rest of the app code:

index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta
      http-equiv="Content-Security-Policy"
      content="default-src 'self'; script-src 'self'"
    />
    <meta
      http-equiv="X-Content-Security-Policy"
      content="default-src 'self'; script-src 'self'"
    />
    <title>Hello from Electron renderer!</title>
  </head>
  <body>
    <h1>Hello from Electron renderer!</h1>
    <p>👋</p>
    <p id="info"></p>
    <div>
        <button id="open-file-manager">View Demo</button>
    </div>
  </body>
  <script src="./renderer.js"></script>
</html>

main:

const { app, BrowserWindow } = require('electron');
const path = require('path');

const createWindow = () => {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
    },
  });

  win.loadFile('index.html');
};

app.whenReady().then(() => {
  createWindow();

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

preload:

const { contextBridge } = require('electron');
const { shell } = require('electron');

contextBridge.exposeInMainWorld('bridge', {
  electron: () => process.versions.electron,
  buttonClick: (link) => shell.openPath(link)
});

renderer:

const information = document.getElementById('info');
information.innerText = `Electron (v${bridge.electron()})`;

const fileManagerBtn = document.getElementById('open-file-manager');

fileManagerBtn.addEventListener('click', (event) => {
  bridge.buttonClick('C:/Users')
});

Error when clicking the button once the app has been launched:

Uncaught Error: Cannot read properties of undefined (reading 'openPath')
    at HTMLButtonElement.<anonymous> (renderer.js:7:10)

I tried with ContextIsolation false and it worked with little modifaction on renderer so I must be missing something. Please help me in this, I have tried to search for an answer but I am not able to find it.


Solution

  • I finally caught what was happening to my app when I reread the electron documentation. It seems that "shell" cannot be used in "sandboxed" scripts and guess what, since electron v20.0.0 the preload script is a sandboxed script.

    Main process can load shell commands so with IPC methods I was able to launch file explorer without deactivating ContextIsolation.