javascript - 如何在 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.js
preload.js
renderer.js
main_window.js
解决方案
编辑
正如另一位用户所问,让我在下面解释我的答案。
在 Electron 中使用的正确方法preload.js
是在您的应用程序可能需要的任何模块周围公开列入白名单的包装器require
。
安全方面,暴露或通过调用require
检索到的任何内容都是危险的(请参阅我的评论以获取更多解释)。如果您的应用程序加载远程内容(很多人会这样做),则尤其如此。require
preload.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>
推荐阅读
- javascript - 我可以/如何通过 URL 参数在 iframe 中调用 Javascript
- jquery - SVG 动画因多个元素而冻结
- twitter-bootstrap - 卡片不透明度设置应用于卡片主体中的图像
- c# - 如何使用 C# 中的共享点 API 在共享点中搜索文档
- javascript - 将ajax调用中返回的数据与JS函数中的数组值相等
- node.js - 使用节点在 docker 容器中执行 shell 脚本
- java - 在 Eclipse IDE 中添加 throws 声明的快捷方式
- github - 如何让我在工作 Github 上的活动出现在我的个人 Github 页面上?
- firebase - 将 Firebase 与自定义身份验证 (JWT) 结合使用
- r - 如何从使用 R 从网站下载的文件中检索特定信息