-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
69 lines (66 loc) · 2.32 KB
/
background.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
chrome.runtime.onInstalled.addListener(() => {
chrome.storage.local.get(['endTime'], (result) => {
if (result.endTime) {
const now = Date.now();
if (result.endTime > now) {
const remainingTime = Math.floor((result.endTime - now) / 1000);
chrome.alarms.create('timer', { when: result.endTime });
updateBadge(remainingTime);
} else {
chrome.storage.local.remove(['endTime']);
}
}
});
});
chrome.alarms.onAlarm.addListener((alarm) => {
if (alarm.name === 'timer') {
chrome.storage.local.remove(['endTime']);
chrome.permissions.contains({permissions: ['notifications']}, (result) => {
if (result) {
chrome.notifications.create({
type: 'basic',
iconUrl: 'icon.png',
title: 'Timer Finished',
message: 'Your timer has finished!'
});
}
});
updateBadge(0);
}
});
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "startTimer") {
const endTime = Date.now() + request.duration * 1000;
chrome.storage.local.set({ endTime: endTime }, () => {
chrome.alarms.create('timer', { when: endTime });
updateBadge(request.duration);
sendResponse({success: true});
});
return true;
} else if (request.action === "stopTimer") {
chrome.alarms.clear('timer');
chrome.storage.local.remove(['endTime']);
updateBadge(0);
sendResponse({success: true});
return true;
} else if (request.action === "getTimeLeft") {
chrome.storage.local.get(['endTime'], (result) => {
if (result.endTime) {
const timeLeft = Math.max(0, Math.floor((result.endTime - Date.now()) / 1000));
sendResponse({ timeLeft: timeLeft });
} else {
sendResponse({ timeLeft: 0 });
}
});
return true;
} else if (request.action === "requestNotificationPermission") {
chrome.permissions.request({permissions: ['notifications']}, (granted) => {
sendResponse({granted: granted});
});
return true;
}
});
function updateBadge(seconds) {
const years = Math.floor(seconds / (365 * 24 * 3600));
chrome.action.setBadgeText({ text: years > 0 ? years.toString() + 'y' : '' });
}