Electron渲染进程奇技淫巧 - 如何访问主进程对象

474 阅读1分钟

❤️ 重要变更

electron内置remote模块在 Electron 14 版本已被移除,现无法直接引入remote模块并使用

🚀 替换方案

使用独立模块@electronic/remote 代替原先的内置模块remote

一、安装 npm/yarn/pnpm install @electronic/remote

二、使用

  1. 主进程设置webPreferences 使渲染进程支持nodeJs API并初始化remote模块
const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
        nodeIntegration: true,
        contextIsolation: false,
        preload: path.join(__dirname, 'preload.js')
    }
})

require(@electron/remote/main).initialize()  // 初始化
require(@electron/remote/main).enable(mainWindow.webContents)  // 获取能力
  1. 渲染进程使用remote模块提供的能力来访问主进程对象
// 渲染进程使用主进程提供的getCurrentWindow打开开发者工具
<button id="devToolBtn">渲染进程打开开发者工具</button>

const btn = document.getElementById('handleOpenDevTool')
btn.addEventListener('click', ()=> {
  const currentWindow = require('@electron/remote').getCurrentWindow()
  currentWindow.webContents.openDevTools()
})
// 渲染进程使用主进程的BrowerWindow对象打开新的窗口
<button id="browserBtn">渲染进程打开新窗口</button>

const btn = document.getElementById('browserBtn')
btn.addEventListener('click', ()=> {
  const BrowserWindow = require('@electron/remote').BrowserWindow
  let win = new BrowserWindow({
      width: 300,
      height: 200
  })
  win.loadFile('xxx.html')
  win.on('close', () => {
      win = null
  })
})