首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >电子IPC通信抛出错误?

电子IPC通信抛出错误?
EN

Stack Overflow用户
提问于 2022-11-10 12:42:53
回答 1查看 41关注 0票数 0

我已经花了好几个小时解决这个问题,但我还是想不出.

下面是我代码的一些部分:

main.js

代码语言:javascript
复制
const electron = require('electron');
const { app, BrowserWindow, ipcMain } = electron;

// ...

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.
    mainWindow.webContents.openDevTools();
};

// ...

ipcMain.on("exit", (evt, arg) => {
    app.quit();
});

index.html

代码语言:javascript
复制
<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="index.css" />
  </head>
  <body>
    <button id="exit">Exit</button>
    <script src="index.js"></script>
  </body>
</html>

index.js

代码语言:javascript
复制
const ipcRenderer = require('electron').ipcRenderer;

document.getElementById("exit").addEventListener("click", function(e) {
    ipcRenderer.send("exit");
});

应用程序应该通过按“退出”按钮来关闭。

我得到的错误是:Uncaught ReferenceError: require is not defined

请帮助我使基本的沟通正确。

我试过使用preload.js,但这使得它更加复杂。

EN

回答 1

Stack Overflow用户

发布于 2022-11-10 13:55:18

您的index.js代码最好作为一个preload.js脚本运行(见下面),它可以访问Node,那么您就不需要节点集成(这可能是一个安全问题).

main.js

代码语言:javascript
复制
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
// ...

const createWindow = () => {
    // Create the browser window.
    const mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js')
        },
    });
    
    // and load the index.html of the app.
    mainWindow.loadFile(path.join(__dirname, 'index.html'));
    
    // Open the DevTools.
    mainWindow.webContents.openDevTools();
};

// ...

ipcMain.on("exit", (evt, arg) => {
    app.quit();
});

preload.js

代码语言:javascript
复制
const { ipcRenderer } = require('electron');

// When document has loaded, initialize
document.onreadystatechange = (event) => {
    if (document.readyState == "complete") {
        document.getElementById('exit').addEventListener("click", event => {
            ipcRenderer.send('exit');
        });
    }
};

index.html

代码语言:javascript
复制
<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="index.css" />
  </head>
  <body>
    <button id="exit">Exit</button>
  </body>
</html>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74389209

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档