无法在电子中使用任何电子或节点相关操作.获取错误过程未定义.我检查了他们指导添加节点支持的各个地方,但这已经完成所以卡在这里我的主要应用程序代码是
Unable to use any electron or node related operations in electron . Getting error process not defined. I Checked at various places they guide to add node Support but that is already Done so stucked here My Main Application code is
const electron = require("electron");
const { app, BrowserWindow } = electron;
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: { nodeIntegration: true },
});
win.loadFile("index.html");
}
app.whenReady().then(createWindow);
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
还有Index.html
And Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello World!</title>
</head>
<body style="background: white">
<h1>Hello World!</h1>
<p>
We are using node
<script>
document.write(process.versions.node);
</script>
, Chrome
<script>
document.write(process.versions.chrome);
</script>
, and Electron
<script>
document.write(process.versions.electron);
</script>
.
</p>
</body>
</html>
更新:下面的答案是一种解决方法.您不应禁用 contextIsolation
,也不应启用 nodeIntegration
.相反,您应该使用 预加载脚本 和 contextBridge API.
Update: the answer below is a workaround. You should not disable contextIsolation
and you should not enable nodeIntegration
. Instead you should use a preload script and the contextBridge API.
在 Electron 12 中,contextIsolation
现在默认为 true
In Electron 12, contextIsolation
is now by default true
如果您将其设置为 false
,您将可以在渲染器进程中访问 Node.js API
If you set it to false
, you will have access to Node.js APIs in the renderer process
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
contextIsolation: false,
nodeIntegration: true
},
});
win.loadFile("index.html");
}
需要注意的是,不推荐这样做!
Electron 维护者更改默认值是有充分理由的.请参阅此讨论
There's a good reason why Electron maintainers changed the default value. See this discussion
如果没有 contextIsolation,渲染器进程中运行的任何代码都可以很容易地进入 Electron 内部或您的预加载脚本,并执行您不希望任意网站执行的特权操作.
Without contextIsolation any code running in a renderer process can quite easily reach into Electron internals or your preload script and perform privileged actions that you don't want arbitrary websites to be doing.
这篇关于无法在渲染器进程中使用 Node.js API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!