我已经花了好几个小时解决这个问题,但我还是想不出.
下面是我代码的一些部分:
main.js
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
<!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
const ipcRenderer = require('electron').ipcRenderer;
document.getElementById("exit").addEventListener("click", function(e) {
ipcRenderer.send("exit");
});应用程序应该通过按“退出”按钮来关闭。
我得到的错误是:Uncaught ReferenceError: require is not defined
请帮助我使基本的沟通正确。
我试过使用preload.js,但这使得它更加复杂。
发布于 2022-11-10 13:55:18
您的index.js代码最好作为一个preload.js脚本运行(见下面),它可以访问Node,那么您就不需要节点集成(这可能是一个安全问题).
main.js
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
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
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<button id="exit">Exit</button>
</body>
</html>https://stackoverflow.com/questions/74389209
复制相似问题