03.electron笔记:electron实战:本地音乐播放器
添加 bootstrap
cnpm install bootstrap --save
构建项目结构
在根目录下创建一个文件夹renderder
,用于存放渲染进程
/
├── main.js
├── package.json
├── renderder/
├── index.html #主页
├── index.js
├── add.html #添加音乐
└── add.js
修改main.js
main.js
:
process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'
const {app, BrowserWindow, ipcMain} = require('electron')
const path = require('path')
let mainWindow;
function createWindow () {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration:true
}
})
mainWindow.loadFile('./renderer/index.html')
}
app.on("ready", () => {
createWindow()
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
主页-创建添加歌曲页面
- index.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>
<button type="button" id="btn-add-music" class="btn btn-primary btn-lg btn-block mt-4">添加歌曲到曲库</button>
</div>
<script>
require('./index.js')
</script>
</body>
</html>
- index.js:
const {ipcRenderer} = require("electron")
document.getElementById("btn-add-music").addEventListener("click", ()=>{
console.log("click");
ipcRenderer.send("add-music-window")
})
- main.js
const {app, BrowserWindow, ipcMain} = require('electron')
...
app.on("ready", () => {
createWindow()
...
ipcMain.on("add-music-window", (event, args)=>{
var addWindow = new BrowserWindow({
width:500,
height:600,
webPreferences: {
nodeIntegration:true
},
parent:mainWindow
});
addWindow.loadFile("./renderer/add.html");
})
})
- add.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Electron 音乐播放器</title>
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-4">
<h1>添加音乐到曲库</h1>
<button type="button" id="btn-add-music" class="btn btn-primary btn-lg btn-block mt-4">选择音乐</button>
</div>
<script>
require('./add.js')
</script>
</body>
</html>
要点解析:
IPC进程间通信
渲染进程index.js
使用IPC
进程间通信
ipcRenderer.send("add-music-window")
让主进程main.js
创建添加窗口
创建子窗口
主进程main.js
创建添加窗口
ipcMain.on("add-music-window", (event, args)=>{
var addWindow = new BrowserWindow({
width:500,
height:400,
webPreferences: {
nodeIntegration:true
},
parent:mainWindow
});
addWindow.loadFile("./renderer/add.html");
其中, parent:mainWindow
添加音乐窗口的父窗口设置为 mainWindow