adrian oviedo
adrian oviedo

Reputation: 684

using electron api from react component

I'm using electron and react, the react app was created with the create-react-app boilerplate. I need to use the electron API to open an external link, but this task is achieve from a react component. I imported the remote electron inside the react component(in order to get access to the current window.) but that gave me an error

const {remote} = require("electron")

The error is raised from electron itself, from node_modules/electron/index.js and the problem is with fs module, it says:

TypeError: fs.existsSync is not a function

This error is showed in the electron windows.

Upvotes: 2

Views: 7142

Answers (3)

Anatol Zakrividoroga
Anatol Zakrividoroga

Reputation: 4518

The answers above are not current.

Here is the correct answer:

Since Electron v12, setting nodeIntegration: true has no affect. Instead, you need to set contextIsolation: false:

mainWindow = new BrowserWindow({
    // ...
    webPreferences: {
        contextIsolation: false,
    }
})

https://github.com/electron/electron/issues/7300#issuecomment-799093768

Upvotes: 0

anni
anni

Reputation: 1463

Encountered the same problem using react-create-app.

The fix, using window.require on the React side instead of import

const electron = window.require("electron")

and on the Electron side, when creating BrowserWindow add nodeIntegration: true as follow

mainWindow = new BrowserWindow({
    width: 900,
    height: 680,
    webPreferences: { nodeIntegration: true }
});

Upvotes: 1

Onno Faber
Onno Faber

Reputation: 661

For typescript:

import { IpcRenderer } from 'electron';

declare global {
  interface Window {
    require: (module: 'electron') => {
      ipcRenderer: IpcRenderer
    };
  }
}

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

See https://github.com/electron/electron/issues/9920

Upvotes: 2

Related Questions