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

2020-02-21  本文已影响0人  CODEOrz

前言

软件包 版本
electron 8.0.1
react 16.12.0

建立通信的方法

初始化
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

"scripts": {
    "electron": "electron .",
    "dev": "electron . --debug",
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
global.electron = require('electron')
const minWindow = () => {
  window.electron.ipcRenderer.send("min");
}

常见问题

mainWindow.webContents.openDevTools()
上一篇 下一篇

猜你喜欢

热点阅读