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

无法在电子中使用任何电子或节点相关的操作。获取错误过程未定义。我检查了他们指导添加节点支持的各个地方,但这已经完成了,所以我的主要应用程序代码是

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

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World!</title>
  </head>
  <body>
    <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。

在Electron 12 中,contextIsolation现在默认是true

如果您将其设置为false,您将可以在渲染器进程中访问 Node.js API

function createWindow() {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: { 
     contextIsolation: false,
     nodeIntegration: true
    },
  });

  win.loadFile("index.html");
}

?? 需要注意的是,不推荐这样做!

Electron 维护者更改默认值是有充分理由的。看到这个讨论

如果没有 contextIsolation,渲染器进程中运行的任何代码都可以很容易地进入 Electron 内部或您的预加载脚本,并执行您不希望任意网站执行的特权操作。

  • @vikrantverma Just adding here that you probably do want to keep `contextIsolation` enabled for security reasons. See the answer [here](https://stackoverflow.com/a/66509352/3479456)

以上是无法在渲染器进程中使用Node.jsAPI的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>