前言
近來因?yàn)椴瓤?,看了許多關(guān)于 React 與 Electron 通信的資料。
利用本文進(jìn)行小結(jié),并在文末指出 隱藏的坑點(diǎn)。本文敘述基于如下環(huán)境:
| 軟件包 | 版本 |
|---|---|
| electron | 8.0.1 |
| react | 16.12.0 |
建立通信的方法
初始化
- create-react-app 初始化react項(xiàng)目
- 安裝electron,并配置main.js如下:
const { app, BrowserWindow } = require('electron')
const path = require('path')
let mainWindow = null
//判斷命令行腳本的第二參數(shù)是否含--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') // 但預(yù)加載的 js 文件內(nèi)仍可以使用 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'))
// ### 接收渲染進(jìn)程的信息
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"
},
- 在項(xiàng)目根目錄下創(chuàng)建 'preload.js' ( 注意:preload.js 作為預(yù)加載項(xiàng)在 main.js 的 preload 配置項(xiàng)中添加,electron初始化時(shí),將向全局添加一個(gè)electron變量)
內(nèi)容如下:
global.electron = require('electron')
- 在 react組件中 直接調(diào)用即可,如:
const minWindow = () => {
window.electron.ipcRenderer.send("min");
}
常見問題
? 一定要注意: 建立通信以后,只能在 electron的界面 中觸發(fā)通信事件,在渲染層對(duì)應(yīng)的Web瀏覽器中操作無效。
看到很多文章提到需要在 public/index.html 中嵌入 <script>,基于本文描述的版本環(huán)境,并不需要這么做。
在 main.js 中,打開調(diào)試模式(本文使用dev命令,開啟debug模式),方便排除問題:
mainWindow.webContents.openDevTools()