Electron學習(三)之簡單交互操作
寫在前面
最近一直在做批量測試工具的開發,打包的exe,執行也是一個黑乎乎的dos窗口,真的醜死了,總感覺沒個界面,體驗不好,所以就想嘗試寫桌面應用程序。
在技術選型時,Java窗體實現使用JavaFx、Swing,感覺都不太理想,為什麼呢?
寫好後,都是通過 Application.launch 啟動,僅能運行一次,不能多次調用(硬傷呀!)。
作為一個測試仔,沒辦法只好找開發了。
於是,我又去找強哥(之前北京同事),強哥給我推薦了electron,我一查,才發現真的太秀了,太好看了吧,結果我就被種草了,真的是太想學了……
需求
故事講完了,開始幹活了,具體需求如下:
- 點擊按鈕可以打開另一個界面
- 按鈕及界面都需要樣式
1、引入樣式
安裝bootstrap命令如下:
npm install bootstrap --save
2、點擊按鈕可以打開另一個界面
在根目錄下創建一個名為renderer的文件夾,並創建index.js,其作用就是向主進程發出通信,具體代碼如下:
const { ipcRenderer } = require('electron')
document.getElementById('add-music').addEventListener("click",()=>{
ipcRenderer.send("add-music-window")
})
再創建一個名為index.html,示例代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<link href="../node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
<title>本地音樂播放器</title>
</head>
<body>
<div class="container m-4">
<h1>我的播放器</h1>
<button type="button" id="add-music" class="btn btn-primary btn-lg btn-block m-4">添加歌曲到曲庫</button>
<!-- Content here -->
</div>
<script src="./index.js"></script>
</body>
</html>
再創建一個名為add.js,示例代碼如下:
const { ipcRenderer } = require('electron')
document.getElementById('add-music').addEventListener("click",()=>{
ipcRenderer.send("add-music-window")
})
再創建一個名為add.html,示例代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>添加音樂</title>
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-4">
<h1>添加音樂到曲庫</h1>
<div id="musicList" class="mb-2">您還未選擇任何音樂文件</div>
<button type="button" id="select-music" class="btn btn-outline-primary btn-lg btn-block mt-4">
選擇音樂
</button>
<button type="button" id="add-music" class="btn btn-primary btn-lg btn-block mt-4">
導入音樂
</button>
</div>
<script>
require('./add.js')
</script>
</body>
</html>
接着再來修改main.js代碼,使用ipcMain來接收渲染進程發起的點擊事件,示例代碼如下:
const { app, BrowserWindow,ipcMain } = require('electron')
const createWindow = () => {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
}
})
win.loadFile('./renderer/index.html')
ipcMain.on("add-music-window",()=>{
const childWin = new BrowserWindow({
width: 500,
height: 300,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
},
parent:win
})
childWin.loadFile('./renderer/add.html')
})
}
app.whenReady().then(() => {
createWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit()
})
效果
npm start 運行查看結果如下:

到此一個簡單點擊交互完成,感興趣的同學可以自己動手去嘗試。

