ipcRenderer not receiving message from main process

孤者浪人 提交于 2020-07-13 02:08:24

问题


I can see the "Hello from renderer" alert, but not the "Goodbye from renderer" alert.

Running in Windows 10.

And I can't see the "received!" alert, which I should see it the ipcRenderer.on(...) worked.

index.js

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

app.on('ready', () => {
  let mainWindow = new BrowserWindow(
  {
    width: 800,
    height: 600,
  });

  mainWindow.loadURL(`file://${__dirname}/index.html`);
  mainWindow.webContents.on('did-finish-load', () => {
    mainWindow.webContents.send("from-main", "teste");
  });
});

index.html

<html>

  <head>
    <title>test</title>

  <script src="./renderer.js"> </script>

  </head>

  <body>
      Wait...
  </body>

</html>

renderer.js

alert('hello from renderer');
const { ipcRenderer } = require('electron');
ipcRenderer.on('from-main', () => { alert('received!');} );
alert('goodbye from renderer');

package.json

{
  "name": "xxx",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "electron ."
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "electron": "^8.0.0"
  }
}

回答1:


let mainWindow = new BrowserWindow(
  {
    width: 800,
    height: 600,
    webPreferences:{
      nodeIntegration:true
    }
  });

Please add nodeIntegration when you are creating the browser window. You are using the Node API at your renderer. When you don't enable nodeIntegration then you won't be able to use any node modules at your renderer js.

To confirm this you can see this error message from your app debug console.

mainWindow.webContents.on('did-finish-load', () => {
    // open dev tools
    mainWindow.webContents.openDevTools()
    mainWindow.webContents.send("from-main", "teste");
  });

Uncaught ReferenceError: require is not defined

This means you didn't enable the nodeIntegration when you are creating the browserWindow.



来源:https://stackoverflow.com/questions/60227586/ipcrenderer-not-receiving-message-from-main-process

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!