ipcRenderer未从主进程接收消息 [英] ipcRenderer not receiving message from main process

查看:206
本文介绍了ipcRenderer未从主进程接收消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以看到来自渲染器的你好警报,但看不到来自渲染器的再见警报。

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

在Windows 10中运行。

Running in Windows 10.

我看不到收到的!警报,我应该看到ipcRenderer.on(...)起作用了。

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

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



index.html

<html>

  <head>
    <title>test</title>

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

  </head>

  <body>
      Wait...
  </body>

</html>



renderer.js



renderer.js

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



package.json



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"
  }
}


推荐答案

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

在创建浏览器窗口时,请添加nodeIntegration。
您正在渲染器上使用Node API。当您未启用nodeIntegration时,将无法在渲染器js上使用任何节点模块。

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");
  });

未捕获的ReferenceError:未定义require

这意味着创建浏览器窗口时未启用nodeIntegration。

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

这篇关于ipcRenderer未从主进程接收消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆