上一篇 electron進(jìn)程間通訊(IPC模塊通訊)
下一篇 【實(shí)戰(zhàn)】electron 制作遠(yuǎn)程控制軟件(預(yù))
目標(biāo): 學(xué)會使用簡單的electron API 解決開發(fā)需求
electron 的主進(jìn)程和渲染進(jìn)程的模塊
- electron 應(yīng)用開發(fā)文檔 :https://www.electronjs.org/docs/api
- 由于我們前面已經(jīng)大概摸清了electron 怎么使用, 下面就直接上關(guān)鍵性代碼
remote 模塊
所屬: 渲染進(jìn)程
功能: 在渲染進(jìn)程中使用主進(jìn)程的模塊
需求: 在窗口中打開一個新窗口
- 目錄結(jié)構(gòu)
learn_electron/
├── package.json
├── main.js
├── remote.js
├── index.html
└── remote.html
// index.html
<button id="btn">打開新窗口</button>
<script src="./remote.js"></script>
// remote.html
<h2>我是通過remote模塊打開的窗口</h2>
// main.js
const { app, BrowserWindow } = require('electron');
// 聲明要打開的主窗口
let mainWindow = null;
app.on('ready', () => {
mainWindow = new BrowserWindow({
width: 800,
height: 800,
// 在渲染進(jìn)程中使用node,remote
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true
}
});
mainWindow.loadFile('index.html'); // 加載網(wǎng)頁
mainWindow.on('close', () => {
mainWindow = null;
})
})
// remote.js
// 從remote模塊中獲取到BrowserWindow
const {BrowserWindow} = require('electron').remote;
window.onload = function () {
const btn = document.querySelector("#btn");
let newWin = null;
btn.onclick = () => {
// 創(chuàng)建新窗口
newWin = new BrowserWindow({
width: 300,
height: 300
})
// 加載新窗口的文件
newWin.loadFile("remote.html");
newWin.on("closed", () => {
newWin = null;
})
}
}

結(jié)果
menu模塊
所屬: 主進(jìn)程
功能: 創(chuàng)建原生應(yīng)用菜單和上下文菜單
需求: 創(chuàng)建簡單原生應(yīng)用菜單和上下文菜單
- Menu.setApplicationMenu(null); 不顯示頂部菜單
- win.webContents.openDevTools(); 打開調(diào)試模式
原生應(yīng)用菜單
// main.js
const { app, BrowserWindow } = require('electron');
let win = null;
app.on('ready', () => {
win = new BrowserWindow({
width: 800,
height: 500,
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true
}
})
// 打開調(diào)試模式
win.webContents.openDevTools();
// 加載menu 相當(dāng)于menu.js 也是主進(jìn)程
require("./menu.js");
win.on("closed", () => {
win = null;
})
})
-------------------------------------------------------------------------
// menu.js
const { Menu, BrowserWindow } = require('electron');
// 菜單模板
let template = [
{
label: "菜單A",
submenu: [ // 子菜單
{
label: "A-1",
accelerator: "ctrl+a", // 設(shè)置菜單快捷鍵
click: () => { // 綁定點(diǎn)擊事件
let win = new BrowserWindow({
width: 300,
height: 300,
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true
}
})
win.loadFile("index.html");
win.on("close", () => {
win = null;
})
}
},
{ label: "A-2", submenu: [{ label: "A-2-2" }] }, // 多級菜單
{ label: "A-3" }
]
},
{
label: "菜單B",
submenu: [
{ label: "B-1" },
{ label: "B-2" },
{ label: "B-3" }
]
}
]
let m = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(m); // 傳入null 則不顯示菜單

結(jié)果
上下文菜單(右鍵菜單)
- contextmenu: h5上下文菜單事件
- remote.getCurrentWindow(): 返回 BrowserWindow 此網(wǎng)頁所屬的窗口
<script>
const { remote } = require('electron');
let template = [
{ label: "復(fù)制", accelerator: "ctrl+c" },
{ label: "粘貼", accelerator: "ctrl+v" }
];
let m = remote.Menu.buildFromTemplate(template);
window.onload = function () {
window.addEventListener("contextmenu", (e) => {
e.preventDefault();
m.popup({ window: remote.getCurrentWindow() })
})
}
</script>

結(jié)果
globalShortcut模塊
所屬: 主進(jìn)程
功能: 在應(yīng)用程序沒有鍵盤焦點(diǎn)時,監(jiān)聽鍵盤事件
需求: 創(chuàng)建和注銷全局快捷鍵
// 注冊快捷鍵
globalShortcut.register('ctrl+e', () => {
win.loadURL("http://m.itdecent.cn"); // 加載網(wǎng)站 http://m.itdecent.cn
})
// 判斷是否注冊快捷鍵成功
const isRegister = globalShortcut.isRegistered("ctrl+e") ? "register true" : "resgister false";
console.log(isRegister); // true/false
app.on('will-quit', () => {
// 注銷單個快捷鍵
globalShortcut.unregistter("ctrl+e");
// 注銷全局快捷鍵
globalShortcut.unregistterAll();
})
clipboard模塊
所屬: 主進(jìn)程、渲染進(jìn)程
功能: 在系統(tǒng)剪貼板上執(zhí)行復(fù)制和粘貼操作。
需求: 復(fù)制一段文字
- clipboard.writeText(text); 復(fù)制一段文字text
<body>
激活碼:
<span id="code">wbrwihfhwhfhwuheruhwue</span>
<button id="btn">復(fù)制激活碼</button>
<script>
const { clipboard } = require('electron');
const code = document.getElementById("code");
const btn = document.getElementById("btn");
btn.onclick = () => {
clipboard.writeText(code.innerHTML);
alert("復(fù)制成功");
}
</script>
</body>
shell模塊
所屬: 主進(jìn)程、渲染進(jìn)程
功能: 使用默認(rèn)應(yīng)用程序管理文件和 url
需求: 在用戶的默認(rèn)瀏覽器中打開 URL
- shell.openExternal(href); 在默認(rèn)瀏覽器中打開href鏈接
const { shell } = require('electron')
shell.openExternal('https://github.com')
需求: 打開子窗口,并接收子窗口的消息
// 打開子窗口
window.open('popup.html');
// 接收信息
window.addEventListener('message', (msg) => {
console.log(msg.data);
})
// popup.html
<body>
<h2>我是彈出子窗口</h2>
<button id="pop-btn">向父窗口傳遞信息</button>
<script>
let btn = document.getElementById("pop-btn");
btn.onclick = (e) => {
window.opener.postMessage("我是子窗口傳遞過來的信息");
}
</script>
</body>
browserView模塊
所屬: 主進(jìn)程
功能: 創(chuàng)建和控制視圖
需求: 創(chuàng)建一個視圖
-
BrowserView被用來讓BrowserWindow嵌入更多的 web 內(nèi)容。 它就像一個子窗口,除了它的位置是相對于父窗口。 這意味著可以替代webview標(biāo)簽.
let bv = new BrowserView();
mainWindow.setBrowserView(bv);
bv.setBounds({ x: 0, y: 100, width: 1000, height: 600 })
bv.webContents.loadURL('https://www.baidu.com')
dialog模塊
所屬: 主進(jìn)程
功能: 顯示用于打開和保存文件、警報等的本機(jī)系統(tǒng)對話框。
需求: 創(chuàng)建一個警告消息
dialog.showMessageBox({
type: "warning",
title: "警告消息title",
message: "我是message",
buttons: ["收到", "忽略"]
}).then(result => {
console.log(result.response) // 數(shù)組下標(biāo)
}).catch(err => {
console.log(err);
})
需求: 打開文件
<button id="btn">打開圖片</button>
<img id="img" style="width: 100%;" src="" alt="">
let btn = document.getElementById("btn");
btn.onclick = () => {
dialog.showOpenDialog({
title: "請選擇照片",
defaultPath: "bg.jpg",
filters: [
{
name: "img",
extensions: ['jpg', "png"], // 只選擇jsp, png
buttonLabel: "確認(rèn)"
}
]
}).then(result => {
console.log(result);
let img = document.getElementById("img");
img.setAttribute("src", result.filePaths[0])
}).catch(err => {
console.log(err);
})
}
需求: 保存一個文件
dialog.showSaveDialog({
title: "保存"
}).then(result => {
console.log(result);
fs.writeFileSync(result.filePath, "aaa")
}).catch(err => {
console.log(err);
})
拓展
- 監(jiān)聽網(wǎng)絡(luò)改變
// online offline 第一次不會觸發(fā), 只能監(jiān)聽網(wǎng)絡(luò)變化
window.ononline = () => {
alert("連上網(wǎng)絡(luò)");
}
window.onoffline = () => {
alert("斷網(wǎng)了。。");
}
- 消息提醒
let option = {
title: "來訂單了",
body: "body"
}
new window.Notification(option.title, option);

END