Electronjs window.require not a function

前端 未结 3 1902
予麋鹿
予麋鹿 2020-12-21 04:51

I\'m using create-react-app (react-scripts v3.0.0) and electronjs (v5.0.1). I\'m trying to pass events from the renderer to main process using the \'icpMain\' module as desc

相关标签:
3条回答
  • 2020-12-21 05:23

    I fix this issue to add webPreferences:{ nodeIntegration: true,preload: '${__dirname}/preload.js}', in electron.js file and add preload.js file in your directory (I added in /public directory where my electron.js file exists)

    electron.js

    mainWindow = new BrowserWindow({
     title: 'Electron App',
     height: 650,
     width: 1140,
     webPreferences: { 
      nodeIntegration: true,
      preload: `${__dirname}/preload.js`,
      webSecurity: false 
     },
     show: false,
     frame: true,
     closeable: false,
     resizable: false,
     transparent: false,
     center: true,
    });
    
    ipcMain.on('asynchronous-message', (event, arg) => {
      console.log(arg); // prints "ping"
      event.reply('asynchronous-reply', 'pong');
    });
    

    preload.js

    in preload.js file just add below line:

    window.ipcRenderer = require('electron').ipcRenderer;
    

    ReactComponent.js

    Write below code in your component function i.e: myTestHandle()

    myTestHandle = () => {
      window.ipcRenderer.on('asynchronous-reply', (event, arg) => {
        console.log(arg); // prints "pong"
      });
      window.ipcRenderer.send('asynchronous-message', 'ping');
    }
    myTestHandle();
    

    or call myTestHandle function anywhere in your component

    0 讨论(0)
  • 2020-12-21 05:30

    It looks like adding the preference:

    var mainWindow = new electron.BrowserWindow({
      ...
      webPreferences: {
        nodeIntegration: true,
      }
    });
    

    is needed to enable require in the renderer process.

    0 讨论(0)
  • 2020-12-21 05:34

    Indeed, you have to set nodeIntegration to true in your BrowserWindow webPreferences since the version 5.0.0 the default values of nodeIntegration and webviewTag are false to improve security. Electron associated PR: 16235

    0 讨论(0)
提交回复
热议问题