简体   繁体   English

渲染过程中 IPCRenderer 的电子错误

[英]Electron Error with IPCRenderer in the render process

Im learning Electron and more nodes, but I keep getting an error everytime I interact with IPC Renderer.我正在学习 Electron 和更多节点,但每次与 IPC Renderer 交互时都会出现错误。

render.js:6 Uncaught ReferenceError: Cannot access 'ipc' before initialization
at updateRP (render.js:6)
at HTMLButtonElement.onclick (index.html:11)

As far as I can tell from various forums, the issue should have been fixed when I added the nodeIntergation to my main process.据我从各种论坛得知,当我将 nodeIntergation 添加到我的主进程时,问题应该已经得到解决。 Im really confused, any help with this would be much appreciated.我真的很困惑,对此的任何帮助将不胜感激。

CODE: HTML代码: HTML

<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
    <link rel="stylesheet" href="index.css">
  </head>
  <body>
    <h1>💖 Hello World!</h1>
    <p>Welcome to your Electron application.</p>
    <button onclick="updateRP()">Update RP</button>
    <script type="text/javascript" src="render.js"></script>
  </body>
</html>

Main主要的

const { app, BrowserWindow } = require('electron');
const { ipcMain } = require('electron');
const ipc = require('electron').ipcMain;
const path = require('path');
const client = require('discord-rich-presence')('745419354375454901');
 
client.updatePresence({
  state: 'slithering',
  details: '🐍',
  startTimestamp: Date.now(),
  endTimestamp: Date.now() + 1337,
  largeImageKey: 'snek_large',
  smallImageKey: 'snek_small',
  instance: true,
});

// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) { // eslint-disable-line global-require
  app.quit();
}

const createWindow = () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  });

  // and load the index.html of the app.
  mainWindow.loadFile(path.join(__dirname, 'index.html'));

  // Open the DevTools.
};

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});


ipcMain.on("UpdateRP", stateForRP =>{
  client.updatePresence({
  state: stateForRP,
  details: 'test',
  startTimestamp: Date.now(),
  endTimestamp: Date.now() + 1337,
  largeImageKey: 'logo',
  smallImageKey: 'profilepic',
  instance: true,
});
});

Render使成为

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

function updateRP(){
    var stateForRP = "Test";
    ipc.send("UpdateRP", stateForRP);
}


In the provided code, the way the destructuring assignment of the object returned by require ('electron') is handled is quite odd, to say the least...在提供的代码中,处理由require ('electron')返回的对象的解构赋值的方式很奇怪,至少可以说......

In renderer :渲染器中

const {ipcRenderer} = require('electron')
const ipc = electron.ipcRenderer; // The variable *electron* has never been defined!

should be:应该:

const electron = require('electron');
const ipc = electron.ipcRenderer;

or:或者:

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

or:或者:

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

Likewise, in main :同样,在main 中

const { app, BrowserWindow } = require('electron');
const { ipcMain } = require('electron');
const ipc = require('electron').ipcMain;

can be rewritten without any redundancy as:可以在没有任何冗余的情况下重写为:

const { app, BrowserWindow, ipcMain } = require('electron');
const ipc = ipcMain;

or even more concisely as:或者更简洁地说:

const { app, BrowserWindow, ipcMain: ipc } = require('electron');

[UPDATE] [更新]

I just noticed another potential issue in the main process code: the variable mainWindow must be global , so that its value doesn't get garbage-collected... See this post .我刚刚注意到主进程代码中的另一个潜在问题:变量mainWindow必须是global ,以便它的值不会被垃圾收集......请参阅这篇文章

Instead of:代替:

const createWindow = () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  });

  // and load the index.html of the app.
  mainWindow.loadFile(path.join(__dirname, 'index.html'));

  // Open the DevTools.
};

use:用:

let mainWindow;

const createWindow = () => {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  });

  // and load the index.html of the app.
  mainWindow.loadFile(path.join(__dirname, 'index.html'));

  // Open the DevTools.
};

It's actually a very simple and easy solution这实际上是一个非常简单易行的解决方案

  1. Ensure the script tag containing the Renderer declaration comes before the html button declaration确保包含 Renderer 声明的脚本标记出现在 html 按钮声明之前

This means the script tag with the Renderer code should be within the <title>...</title> block这意味着带有渲染器代码的脚本标签应该在<title>...</title>块内

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM