# 6.跨进程调用

# Remote (渲染进程中使用主进程)

. xcooo

在渲染进程中使用主进程模块

进程: 渲染进程

remote 模块为渲染进程 (web页面) 和 主进程通信 (IPC) 提供了一种简单方法

在 Electron中, GUI相关的模块 (如 dialog, menu等), 仅在主进程中可用, 在渲染进程中不可用, 为了在渲染进程中使用它们, ipc模块是向主进程发送进程间消息是所必需的. 使用 remote模块, 你可以调用 main 进程对象的方法, 而不必显式发送进程间消息, 类似与 java的 RML

例如: 从渲染进程创建浏览器窗口

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

注意: 反过来 (如果需要从主进程访问渲染进程), 可以使用 webContents.executeJavascript

注意事项: 因为安全原因, remote 模块能在一下几种情况下被禁用

  • BrowserWindow - 通过设置 enableRemoteModule 选项为 false
  • <webview> - 通过 enableremotemodule 属性设置成 false

# 主进程访问渲染进程

用法:

contents.executeJavaScript(code, userGesure)
1
  • code String
  • userGesture Boolean(options) - Default false

在页面执行 code

在浏览器窗口中, 一些HTML API (如requestFullScreen) 只能是 由来自用户的手势调用, 将userGesture 设置 为 true 将删除此限制

Code execution will be suspended until web page stop loading

contents.executeJavaScript('fetch(https://jsonplaceholder.tyicode.com/users/1").then(resp => resp.json())', true)
	.then(result) => {
    console.log(result) // will be the JSON object sfrom the fetch call
}
1
2
3
4

Example: 点击百度logo即可关闭窗口

'use strict'

const APP = {
    version: '1.0.0',
    author: 'uffy@qq.com',
    root: __dirname,
    debug: true
}
1
2
3
4
5
6
7
8
上次更新: 2021/2/21 下午7:52:17