首页 > 解决方案 > 如何在 Electron 中正确使用 preload.js

问题描述

我正在尝试fs在我的renderer流程中使用 Node 模块(在此示例中为 ),如下所示:

// main_window.js
const fs = require('fs')

function action() {
    console.log(fs)
}

注意:action当我按下我的main_window.

但这给出了一个错误:

Uncaught ReferenceError: require is not defined
    at main_window.js:1

正如这个接受的答案所建议的那样main.js,我可以通过在初始化时将这些行添加到 my来解决这个问题main_window

// main.js
main_window = new BrowserWindow({
    width: 650,
    height: 550,
    webPreferences: {
        nodeIntegration: true
    }
})

但是,根据文档,这不是最好的做法,我应该创建一个preload.js文件并在那里加载这些 Node 模块,然后在我的所有renderer进程中使用它。像这样:

main.js

main_window = new BrowserWindow({
    width: 650,
    height: 550,
    webPreferences: {
        preload: path.join(app.getAppPath(), 'preload.js')
    }
})

preload.js

const fs = require('fs')

window.test = function() {
    console.log(fs)
}

main_window.js

function action() {
    window.test()
}

它有效!


现在我的问题是,我应该在(因为只有在我可以访问 Node 模块)中编写我的renderer进程的大部分代码,然后只调用每个文件中的函数(例如这里,),这不是违反直觉的吗?? 我在这里不明白什么?preload.jspreload.jsrenderer.jsmain_window.js

标签: javascriptnode.jselectron

解决方案


编辑

正如另一位用户所问,让我在下面解释我的答案。

在 Electron 中使用的正确方法preload.js是在您的应用程序可能需要的任何模块周围公开列入白名单的包装器require

安全方面,暴露或通过调用require检索到的任何内容都是危险的(请参阅我的评论以获取更多解释)。如果您的应用程序加载远程内容(很多人会这样做),则尤其如此。requirepreload.js

为了正确地做事,您需要启用很多选项,BrowserWindow如下所述。设置这些选项会强制您的电子应用程序通过 IPC(进程间通信)进行通信,并将两个环境相互隔离。像这样设置您的应用程序可以让您验证require后端中可能是“d”模块的任何内容,这些模块不会被客户端篡改。

下面,您将找到一个简短示例,说明我所说的内容以及它在您的应用中的外观。如果您刚开始,我可能会建议使用secure-electron-template(我是其作者)在构建电子应用程序时从一开始就包含所有这些安全最佳实践。

此页面还提供了有关使用 preload.js 制作安全应用程序时所需的架构的良好信息。


main.js

const {
  app,
  BrowserWindow,
  ipcMain
} = require("electron");
const path = require("path");
const fs = require("fs");

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win;

async function createWindow() {

  // Create the browser window.
  win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: false, // is default value after Electron v5
      contextIsolation: true, // protect against prototype pollution
      enableRemoteModule: false, // turn off remote
      preload: path.join(__dirname, "preload.js") // use a preload script
    }
  });

  // Load app
  win.loadFile(path.join(__dirname, "dist/index.html"));

  // rest of code..
}

app.on("ready", createWindow);

ipcMain.on("toMain", (event, args) => {
  fs.readFile("path/to/file", (error, data) => {
    // Do something with file contents

    // Send result back to renderer process
    win.webContents.send("fromMain", responseObj);
  });
});

preload.js

const {
    contextBridge,
    ipcRenderer
} = require("electron");

// Expose protected methods that allow the renderer process to use
// the ipcRenderer without exposing the entire object
contextBridge.exposeInMainWorld(
    "api", {
        send: (channel, data) => {
            // whitelist channels
            let validChannels = ["toMain"];
            if (validChannels.includes(channel)) {
                ipcRenderer.send(channel, data);
            }
        },
        receive: (channel, func) => {
            let validChannels = ["fromMain"];
            if (validChannels.includes(channel)) {
                // Deliberately strip event as it includes `sender` 
                ipcRenderer.on(channel, (event, ...args) => func(...args));
            }
        }
    }
);

索引.html

<!doctype html>
<html lang="en-US">
<head>
    <meta charset="utf-8"/>
    <title>Title</title>
</head>
<body>
    <script>
        window.api.receive("fromMain", (data) => {
            console.log(`Received ${data} from main process`);
        });
        window.api.send("toMain", "some data");
    </script>
</body>
</html>

推荐阅读