Unable to use Node.js APIs in renderer process(无法在渲染器进程中使用 Node.js API)
问题描述
无法在电子中使用任何电子或节点相关操作.获取错误过程未定义.我检查了他们指导添加节点支持的各个地方,但这已经完成所以卡在这里我的主要应用程序代码是
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无法在渲染器进程中使用 Node.js API
基础教程推荐
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 动态更新多个选择框 2022-01-01