美文网首页
React 与 Electron 建立通信的方法及常见问题

React 与 Electron 建立通信的方法及常见问题

作者: CODEOrz | 来源:发表于2020-02-21 11:33 被阅读0次

前言

  • 近来因为踩坑,看了许多关于 React 与 Electron 通信的资料。
    利用本文进行小结,并在文末指出 隐藏的坑点

  • 本文叙述基于如下环境:

软件包 版本
electron 8.0.1
react 16.12.0

建立通信的方法

初始化
  • create-react-app 初始化react项目
  • 安装electron,并配置main.js如下:
const { app, BrowserWindow } = require('electron')
const path = require('path')
let mainWindow = null
//判断命令行脚本的第二参数是否含--debug
const debug = /--debug/.test(process.argv[2])
function makeSingleInstance() {
  if (process.mas) return
  app.requestSingleInstanceLock()
  app.on('second-instance', () => {
    if (mainWindow) {
      if (mainWindow.isMinimized()) mainWindow.restore()
      mainWindow.focus()
    }
  })
}
function createWindow() {
  const windowOptions = {
    width: 1200,
    height: 760,
    webPreferences: {
      javascript: true,
      plugins: true,
      nodeIntegration: true,
      webSecurity: false,
      preload: path.join(__dirname, 'preload.js') // 但预加载的 js 文件内仍可以使用 Nodejs 的 API
    },
  }
  mainWindow = new BrowserWindow(windowOptions)
  mainWindow.loadURL("http://localhost:3000/")
  // mainWindow.loadURL(path.join('file://', __dirname, '/build/index.html'))
  // mainWindow.loadURL(path.join('file://', __dirname, './index.html'))
  // ### 接收渲染进程的信息
  const ipc = require('electron').ipcMain
  ipc.on('min', function () {
    mainWindow.minimize()
  })
  ipc.on('max', function () {
    mainWindow.maximize()
  })
  ipc.on("login", function () {
    mainWindow.maximize()
  })
  if (debug) {
    mainWindow.webContents.openDevTools()
    require('devtron').install()
  }
  mainWindow.on('closed', () => {
    mainWindow = null
  })
}
makeSingleInstance()
app.on('ready', () => {
  createWindow()
})
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
})
module.exports = mainWindow

  • 更改package.json如下:
"scripts": {
    "electron": "electron .",
    "dev": "electron . --debug",
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  • 在项目根目录下创建 'preload.js' ( 注意:preload.js 作为预加载项在 main.js 的 preload 配置项中添加,electron初始化时,将向全局添加一个electron变量)
    内容如下:
global.electron = require('electron')
  • 在 react组件中 直接调用即可,如:
const minWindow = () => {
  window.electron.ipcRenderer.send("min");
}

常见问题

  • 一定要注意: 建立通信以后,只能在 electron的界面 中触发通信事件,在渲染层对应的Web浏览器中操作无效。

  • 看到很多文章提到需要在 public/index.html 中嵌入 <script>,基于本文描述的版本环境,并不需要这么做。

  • 在 main.js 中,打开调试模式(本文使用dev命令,开启debug模式),方便排除问题:

mainWindow.webContents.openDevTools()

相关文章

网友评论

      本文标题:React 与 Electron 建立通信的方法及常见问题

      本文链接:https://www.haomeiwen.com/subject/gffcqhtx.html