编辑
正如另一位用户所问,让我在下面解释我的答案.
使用preload.js
英寸Electron的正确方法是在应用程序可能需要安装的任何模块周围expose 白名单包装.
在安全方面,expose require
或通过preload.js
中的require
调用检索到的任何内容都是危险的(更多解释请参见my comment here).如果你的应用程序加载远程内容,这一点尤其正确,很多应用程序都会加载远程内容.
为了把事情做好,你需要在你的BrowserWindow
上启用很多选项,我将在下面详细介绍.设置这些选项将强制您的Electron 应用程序通过IPC(进程间通信)进行通信,并将这两个环境彼此隔离.通过这样设置应用程序,您可以验证后端中可能是require
'd模块的任何内容,而客户端不会对其进行篡改.
下面,你会发现一个简短的例子,我说的是什么,以及它在你的应用程序中的外观.如果你刚刚开始,我可能会建议你使用secure-electron-template
(我是这本书的作者),它在构建Electron 应用程序时,从一开始就具备了所有这些安全最佳实践.
This page还提供了有关使用预加载时所需架构的良好信息.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>