电子节点集成不工作,也一般奇怪的电子行为



我是新来的电子,我真的一直在努力使它工作。我正在经历我无法解释的行为,所以这里是一个总结:我无法使电子和html之间的通信工作

"Uncaught ReferenceError: require is not defined"在网站内部,即使我有nodeIntegration:true

File Tree:
./
index.html
index.js
package-lock.json
package.json
node_modules/

index.js:

const electron = require("electron");
const Ffmpeg = require("fluent-ffmpeg");
const CmdExec = require('child_process');
const {
app,
BrowserWindow,
ipcMain
} = electron;
function createWindow() {
//If I put the main window ini into here, and then call app.on("ready", createWindow()); app says
//"Cant create window before ready", even though I just moved the funcion from inside ready to here..
}
app.on('ready', () => {
mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true
}
});
mainWindow.loadURL(`${__dirname}/index.html`);
});
ipcMain.on("video:submit", (event, path) =>{
CmdExec.exec("echo hello", (value)=>{console.log(value)});
});

html:

<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
</head>
<body>
<h1>WELCOME!</h1>
<script src="" async defer></script>
<form action="">
<div>
<br>
<label for=""></label>
<input type="file" accept="video/*" name="" id="">
</div>
<button type="submit">get info</button>
</form>
<script>
const electron = require("electron");
electron.send('perform-action', args);
document.querySelector("form").addEventListener("submit", (event) => {
event.preventDefault();
const {path} = document.querySelector("input").files[0];
window.api.send("video:submit", path);
});
//Tried multiple methos Ive found on stackoverflow,, dont think I implemented them right 
//though
</script>
</body>
</html>

package.json:

{
"name": "media_encoder",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"electron": "electron ."
},
"author": "",
"license": "ISC",
"dependencies": {
"electron": "^12.0.0"
}
}

Electron 12现在将contextIsolation默认为true,这禁用了Node(这里是发行说明;这是PR)。

下面是对这个变化的讨论。nodeIntegration的价值将在未来的电子版本中被删除。

修复此问题的最简单方法是禁用上下文隔离:

mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});

也就是说,出于安全原因,您可能需要考虑启用contextIsolation。请参阅本文档,解释为什么此功能可以增强应用程序的安全性。

最新更新