xb18
xb18
文章39
标签0
分类0
electron

electron

初始

开发环境

1
2
3
4
5
6
// 区分生产和开发环境
if (app.isPackaged) {
win.loadFile('dist/index.html');
} else {
win.loadURL('http://localhost:8888/');
}

进程间通信

通过ipcMain 和 ipcRenderer实现主进程和渲染进程间通信,以及暴露到JS脚本(预加载脚本)

主进程向渲染进程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// main.js 主进程
mainWindow.webContents.send('update-counter', 234)

// preload.js 渲染进程 暴露到window.electronAPI
contextBridge.exposeInMainWorld('electronAPI', {
handleCounter: (callback) => ipcRenderer.on('update-counter', callback) // 监听主进程事件
});

// renderer.js 预加载脚本
window.electronAPI.handleCounter((event, value) => {
// value: 234
const oldValue = Number(counter.innerText)
const newValue = oldValue + value
counter.innerText = newValue
event.sender.send('counter-value', newValue)
})

渲染进程到主进程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// main.js
ipcMain.on('set-title', (event, title) => {
const webContents = event.sender
const win = BrowserWindow.fromWebContents(webContents)
win.setTitle(title)
})

// preload.js
contextBridge.exposeInMainWorld('electronAPI', {
setTitle: (title) => ipcRenderer.send('set-title', title)
})

// renderer.js JS脚本
window.electronAPI.setTitle(title)

文件下载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const {
app, BrowserWindow, Menu, ipcMain, session,
} = require('electron');
const path = require('path');
const os = require('os');

session.defaultSession.on('will-download', (event, item, webContents) => {
const fileName = item.getFilename();
const _path = path.join(os.homedir(), `Downloads/${fileName}`);
item.setSavePath(_path);
item.once('done', (event, state) => {
if (state === 'completed') {
require('fs').chmodSync(_path, 0o444);
// const message = `下载完成,保存至${_path}`;
console.log(`downloadCompleted: ${_path}`);
win.webContents.send('downloadCompleted', _path);
}
console.log(`Download status: ${state}`);
});
});

存储lowdb

本文作者:xb18
本文链接:http://xb18.github.io/2023/10/27/electron/
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可