【发布时间】:2022-11-10 21:59:46
【问题描述】:
我现在解决了几个小时的问题,但我仍然无法弄清楚......
以下是我的代码的一些部分:
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();
});
索引.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,但这让它变得更加复杂。
【问题讨论】:
-
阅读context isolation。也可以在nodeIntegration下添加
contextIsolation: false但不推荐 -
是的,这行得通。但它更多的是一种解决方法,而不是一个干净有效的解决方案
标签: javascript electron ipc