Theme NexT works best with JavaScript enabled
0%

基于Electron的番茄钟

^ _ ^

应用搭建

1
2
3
4
mkdir tomato_clock
cd tomato_clock
npm init
cnpm install electron --save-dev

package.json中添加

1
2
3
"scripts": {
"start": "electron ."
}

渲染页面index.html

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
</head>
<body>
<div id="timer-container"></div>
<!-- You can also require other files to run in this process -->
<script src="./renderer.js"></script>
</body>
</html>

渲染进程renderer.js

首先需要下载 timer.js 模块

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
const {ipcRenderer} = require('electron')
const Timer = require('timer.js')

function startWork(){
let workTimer = new Timer({
onclick: (ms) => {
updateTime(ms)
},
onend: () => {
notification()
}
})
// 启动10s
workTimer.start(10)
}

function updateTime(ms){
let timeContainer = document.getElementById('timer-container')
let s = (ms / 1000).toFixed(0)
let ss = s % 60
let mm = (s / 60).toFixed(0)
timeContainer.innerText = `${mm.toString().padStart(2, 0)}: ${ss.toString.padStart(2, 0)}`
}

async function notification(){
let res = await ipcRenderer.invoke('work-notification')
if(res === 'rest'){
setTimeout(() => {
alert('休息')
}, 5 * 1000)
}
else if(res === 'work'){
startWork()
}
}

startWork()

主进程main.js

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
const {app, BrowserWindow, Notification, ipcMain} = require('electron')

let win
app.on('ready', () => {
win = new BrowserWindow({
width: 300,
height: 300,
webPreferences: {
nodeIntegration: true
}
})
win.loadFile('./index.html')
handleIPC()
})

function handleIPC(){
ipcMain.handle('work-notification', async function () {
let res = await new Promise((resolve, reject) => {
let notification = new Notification({
title: '任务结束',
body: '是否开始休息',
actions: [{text: '开始休息', type: 'button'}],
closeButtonText: '继续工作'
})
notification.show()
notification.on('action', () => {
resolve('rest')
})
notification.on('close', () => {
resolve('work')
})
})
return res
})
}

启动进程

1
npm start