远程 | remote

使用呈现程序进程中的主处理模块。

过程:渲染器

remote
dialogmenuipcremote
const {BrowserWindow} = require('electron').remote
let win = new BrowserWindow({width: 800, height: 600})
win.loadURL('https://github.com')

注意:对于反向操作(从主进程访问渲染器进程),可以使用webContents.executeJavascript。

远程对象

remote
BrowserWindowwinnew BrowserWindowBrowserWindowBrowserWindowwin

注意:只有第一次引用远程对象时才存在的可枚举属性可通过远程访问。

remote

远程对象的生命周期

Electron 确保只要渲染器进程中的远程对象处于活动状态(换句话说,未被垃圾收集),主进程中的相应对象将不会被释放。当远程对象被垃圾回收后,主进程中的相应对象将被解除引用。

如果远程对象在渲染器进程中泄漏(例如存储在地图中但从未释放),则主进程中的相应对象也将泄漏,因此应该非常小心,不要泄漏远程对象。

但是,字符串和数字等主值类型是通过复制发送的。

将回调传递给主流程

remote

首先,为了避免死锁,异步调用传递给主进程的回调。您不应该期望主进程获得传递的回调的返回值。

Array.map
// main process mapNumbers.js
exports.withRendererCallback = (mapper) => {
  return [1, 2, 3].map(mapper)
}

exports.withLocalCallback = () => {
  return [1, 2, 3].map(x => x + 1)
}
// renderer process
const mapNumbers = require('electron').remote.require('./mapNumbers')
const withRendererCb = mapNumbers.withRendererCallback(x => x + 1)
const withLocalCb = mapNumbers.withLocalCallback()

console.log(withRendererCb, withLocalCb)
// [undefined, undefined, undefined], [2, 3, 4]

如您所见,渲染器回调的同步返回值与预期不符,并且与主流程中存在的相同回调的返回值不匹配。

其次,传递给主进程的回调将持续到主进程垃圾收集为止。

close
require('electron').remote.getCurrentWindow().on('close', () => {
  // window was closed...
})

但请记住,直到您明确地卸载它之前,回调才会被主进程引用。如果您不这样做,每次重新加载窗口时都会重新安装回调函数,每次重新启动都会泄漏一个回调函数。

close

为避免此问题,请确保清除对传递给主进程的渲染器回调的任何引用。这涉及清理事件处理程序,或者确保主进程明确地被告知参考来自正在退出的渲染器进程的回调。

访问主进程中的内置模块。

remoteelectron
const app = require('electron').remote.app
console.log(app)

方法

remote
remote.require(module)
moduleanyrequire(module)remote.getCurrentWindow()BrowserWindowremote.getCurrentWebContents()WebContentsremote.getGlobal(name)
name
anynameglobal[name]

属性

remote.process
processremote.getGlobal('process')
远程 | remote