初见Electron

Artificial-Fool Lv3

https://www.electronjs.org/zh/docs/latest/tutorial/quick-start

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// main.js

// Modules to control application life and create native browser window
const { app, BrowserWindow, ipcMain } = require('electron/main');
const path = require('node:path');

const createWindow = () => {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 700,
frame: false,//无边框
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
},
});

// 加载 index.html
mainWindow.loadFile('index.html');

// 打开开发工具
// mainWindow.webContents.openDevTools()
};

// 这段程序将会在 Electron 结束初始化
// 和创建浏览器窗口的时候调用
// 部分 API 在 ready 事件触发后才能使用。
app.whenReady().then(() => {
ipcMain.handle('ping', () => 'pong');
createWindow();

app.on('activate', () => {
// 在 macOS 系统内, 如果没有已开启的应用窗口
// 点击托盘图标时通常会重新创建一个新窗口
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});

// 除了 macOS 外,当所有窗口都被关闭的时候退出程序。 因此, 通常
// 对应用程序和它们的菜单栏来说应该时刻保持激活状态,
// 直到用户使用 Cmd + Q 明确退出
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});

// 在当前文件中你可以引入所有的主进程代码
// 也可以拆分成几个文件,然后用 require 导入。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// preload.js

// 所有的 Node.js API接口 都可以在 preload 进程中被调用.
// 它拥有与Chrome扩展一样的沙盒。
window.addEventListener('DOMContentLoaded', () => {
const replaceText = (selector, text) => {
const element = document.getElementById(selector);
if (element) element.innerText = text;
};

for (const dependency of ['chrome', 'node', 'electron']) {
replaceText(`${dependency}-version`, process.versions[dependency]);
}
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const { contextBridge, ipcRenderer } = require('electron');

contextBridge.exposeInMainWorld('versions', {
node: () => process.versions.node,
chrome: () => process.versions.chrome,
electron: () => process.versions.electron,
ping: () => ipcRenderer.invoke('ping'),
// 除函数之外,我们也可以暴露变量
});
const func = async () => {
const response = await window.versions.ping();
console.log(response); // 打印 'pong'
};

func();

1
2
3
4
5
6
7
.between {
font-size: 1.4rem;
position: absolute;
top: 2rem;
right: 2rem;
-webkit-app-region: drag;/*定义拖动区域*/
}
  • Title: 初见Electron
  • Author: Artificial-Fool
  • Created at : 2024-12-13 18:00:00
  • Updated at : 2024-12-17 10:10:04
  • Link: https://space.bilibili.com/636023121/2024/12/13/ElectronFirstTry/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments
On this page
初见Electron