编辑
正如另一位用户所问,让我在下面解释我的答案。
在 Electron 中使用 preload.js 的正确方法是将您的应用可能需要的任何模块周围的白名单包装器暴露给 require。
在安全方面,暴露require 或通过require 调用在preload.js 中检索到的任何内容是很危险的(请参阅my comment here 了解更多解释原因)。如果您的应用加载远程内容(很多人都会这样做),则尤其如此。
为了正确地做事,您需要在BrowserWindow 上启用很多选项,如下所述。设置这些选项会强制您的电子应用程序通过 IPC(进程间通信)进行通信,并将两个环境相互隔离。像这样设置您的应用程序可以让您验证后端中可能是 require'd 模块的任何内容,而客户端不会对其进行篡改。
您将在下面找到一个简短示例,说明我所说的内容以及它在您的应用中的外观。如果您刚开始,我可能会建议使用 secure-electron-template(我是其作者),它在构建电子应用程序时从一开始就包含了所有这些安全最佳实践。
This page 还提供了有关使用 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));
}
}
}
);
index.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>