无法在渲染器进程中使用 Node.js API

时间:2023-01-29
本文介绍了无法在渲染器进程中使用 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:使用 require(lib) 与 &lt;script&gt;在电子应用程序中 下一篇:Electron - 如何添加外部文件?

相关文章

最新文章