remote 模块
Electron 主进程和渲染进程中的模块(介绍)
remote 模块
remote
模块提供了一种在 渲染进程(网页)
和 主进程
之间进行进程间通讯 (IPC)
的简便途径。
Electron
中, 与 GUI
相关的模块(如 dialog, menu 等)只存在于主进程,而不在渲染进程中。
为了能从渲染进程中使用它们,需要用 ipc
模块来给主进程发送进程间消息。使用 remote
模块,
可以调用主进程对象的方法,而无需显式地发送进程间消息,这类似于 Java
的 RMI
。
Electron10.x
之前可以直接使用 Remote
模块, Electron10.x
以后 Electron14.x
以前要使用 remote
模块的话必须得在 BrowserWindow
中通过 enableRemoteModule: true
开启,
Electron14.x
以后官方把内置的 remote
挪到了第三方模块里面,下面我们给大家看看如何在 Electron
最新版本中使用
@electron/remote
模块。
渲染进程中通过 remote 模块调用主进程中的 BrowserWindow 打开新窗口
1. 安装 @electron/remote
npm install --save @electron/remote
yarn add @electron/remote
pnpm install --save @electron/remote
2. 主进程中配置启用 remote 模块
const remote=require(’@electron/remote/main’)
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
});
//启用 Remote 模块
remote.initialize()
remote.enable(mainWindow.webContents);
3. 渲染进程引入 remote 模块使用
const btn = document.querySelector('#btn');
const path = require('path');
const { BrowserWindow } = require("@electron/remote")
btn.onclick = () => {
win = new BrowerWindow({
width: 300,
height: 200,
frame: false,
transparent: true
// fullscreen:trues
})
win.loadURL(path.join('file:' ,__dirname, 'news.html'));
win.on('close',() => {
win = null
});
}
网页安全政策 Content-Security-Policy
Content Security Policy
简称 CSP
是一种网页安全政策 CSP
的实质就是 白名单
制度,
开发者明确告诉客户端,哪些外部资源可以加载和执行,等同于提供 白名单
。它的实现和执行全部由浏览器完成,
开发者只需提供配置。 CSP
大大增强了网页的安全性。攻击者即使发现了漏洞,也没法注入脚本,
除非还控制了一台列入了 白名单
的可信主机。 通俗的讲开启 CSP
后可以让浏览器自动禁止外部注入恶意脚本,增加网站的安全性能。
从 2.0
版本开始,如果使用 electron
的开发人员没有定义 Content-Security-Policy
,
Electron
就会在 DevTool console
发出警告提示,如下图:
配置 Content-Security-Policy
两种方式的规则都是一样的,default-src
代表默认规则,'self'
表示限制所有的外部资源,只允许当前域名加载资源。
<meta http-equiv="Content-Security-Policy" content="default-src 'self'">
一般情况下,默认规则可以包揽大多数的需求,但凡事都有例外,资源繁多的时候通常需要特殊配置,最值得关心的是 script
的安全,
这至关重要,一旦被注入恶意 script
,很多安全 控制就会荡然无存,可以使用 script-src
这一指令设置:
<meta http-equiv="Content-Security-Policy" content="script-src 'self'">
例如我们要引入 google-analytics 分析流量,可以这样设置:
<meta http-equiv="Content-Security-Policy" content="script-src 'self' https://www.google-analytics.com">