【问题标题】:Electron - Setting up IPC communication between main and renderer processesElectron - 在主进程和渲染器进程之间设置 IPC 通信
【发布时间】:2021-12-04 21:46:46
【问题描述】:

我正在使用https://github.com/maxogden/menubar 使用 Electron 创建一个菜单栏桌面应用程序。但是,我正在努力设置基本的 IPC 通信。知道为什么下面的代码不起作用吗?为了澄清这一点,我希望test 在应用程序启动时退出到控制台,但事实并非如此。

app.js

const { app } = require('electron');
const Menubar = require('menubar');

const menubar = Menubar.menubar({
  index: `file://${__dirname}/index.html`,
  preloadWindow: true,
  icon: './assets/img/icon.png',
});

try {
  require('electron-reloader')(module)
} catch (_) { }

app.on('ready', () => {
  menubar.window.webContents.send('test');
});

renderer.js

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

ipcRenderer.on('test', () => {
  console.log('test');
});

index.html

<html>
<head>
  <title>Test</title>
  <script>
    require('./renderer')
  </script>
</head>
<body>
</body>
</html>

【问题讨论】:

    标签: javascript electron


    【解决方案1】:

    这可能是假阴性。

    我希望在应用程序启动时将测试注销到控制台,但事实并非如此。

    console.log 调用的输出位置取决于进行这些调用的位置:

    • 从主线程:查看启动应用程序的终端。

    • 从渲染器线程:查看 Chrome DevTools 控制台。

    所以请确保您在正确的位置寻找预期的输出。

    如果这不起作用,那么这里有一个关于如何在主进程和渲染器进程之间设置 IPC 通信的小演示。

    ma​​in.js

    您会注意到我确实将nodeIntegrationcontextIsolation 都设置为它们的默认值。这样做是为了明确您无需降低应用的安全栏即可允许在主进程和渲染器进程之间发送消息。

    这是怎么回事?

    主进程等待渲染器完成加载,然后发送“ping”消息。 IPC 通信将由预加载脚本处理。

    注意console.log 调用,看看它在下面的截屏视频中出现的位置。

    const {app, BrowserWindow} = require('electron'); // <-- v15
    const path = require('path');
    
    app.whenReady().then(() => {
      const win = new BrowserWindow({
        webPreferences: {
          devTools: true,
          preload: path.resolve(__dirname, 'preload.js'),
          nodeIntegration: false, // <-- This is the default value
          contextIsolation: true  // <-- This is the default value
        }
      });
      win.loadFile('index.html');
      win.webContents.openDevTools();
      win.webContents.on('did-finish-load', () => {
        win.webContents.send('ping', '?');
      });
      // This will not show up in the Chrome DevTools Console
      // This will show up in the terminal that launched the app
      console.log('this is from the main thread');
    });
    

    preload.js

    我们正在使用contextBridge API。这允许在不启用 nodeIntegration 或破坏上下文隔离的情况下向渲染器进程公开特权 API。

    API 将在一个非常愚蠢的命名空间 (BURRITO) 下可用,以表明您可以更改它。

    const { contextBridge, ipcRenderer } = require('electron');
    
    contextBridge.exposeInMainWorld('BURRITO', {
      whenPing: () => new Promise((res) => {
        ipcRenderer.on('ping', (ev, data) => {
          res(data);
        });
      })
    });
    

    renderer.js

    使用预加载脚本提供的 API,我们开始监听 ping 消息。当我们得到它时,我们将主进程通信的数据放在渲染器页面中。我们还记录了一条消息,您可以在下面的截屏视频中看到。

    BURRITO.whenPing().then(data => {
      document.querySelector('div').textContent = data;
      // This will show up in the Chrome DevTools Console
      console.log(`this is the renderer thread, received ${data} from main thread`);
    });
    

    index.html

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <title>IPC Demo</title>
      </head>
      <body>
        <div></div>
        <script src="./renderer.js"></script>
      </body>
    </html>
    

    运行应用程序:

    npx electron main.js
    

    您可以看到两个console.log 调用在两个不同的地方产生了输出。

    【讨论】:

    • 谢谢,效果很好!
    【解决方案2】:

    要使用 IPC 通信,您必须启用 nodeIntegration。我会尝试类似的东西

    const menubar = Menubar.menubar({
      index: `file://${__dirname}/index.html`,
      preloadWindow: true,
      icon: './assets/img/icon.png',
      browserWindow:{
        webPreferences: {nodeIntegration: true},
      },
    });
    

    【讨论】:

    • To use IPC communication you have to enable nodeIntegration. — 这实际上是不正确的,并且无缘无故地对安全性产生负面影响。
    猜你喜欢
    • 1970-01-01
    • 2021-07-24
    • 2016-12-08
    • 2021-05-13
    • 1970-01-01
    • 2022-01-11
    • 2017-06-01
    • 2018-06-13
    • 2018-05-05
    相关资源
    最近更新 更多