-
Notifications
You must be signed in to change notification settings - Fork 1
/
background.js
78 lines (67 loc) · 2.85 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
70
71
72
73
74
75
76
77
78
function getKeyFromStorage (key) {
// getKeyFromStorge: wrapper for chrome.storage.local.get(),
// return promise containing the value of provided key
return new Promise((resolve, _) => {
chrome.storage.local.get( key, result => resolve(result[key]) );
});
}
// prompt user to configure after install
chrome.runtime.onInstalled.addListener(i => {
if (i.reason == 'install') {
// wait 1 sec before opening the window to prevent the browser from stealing the focus
setTimeout(() => {
chrome.windows.create({url: 'popup.html', type: 'popup', height: 300, width: 450 })
}, 1000);
}
});
(async () => {
const notification_id = 'batteryLevelAlert',
battery = await navigator.getBattery(),
do_not_show_notification_again = await getKeyFromStorage('do_not_show_notification_again');
let notification_exist = notification_showed = false;
// clear battery level notification (if exist) when the device connected to a power adapter
battery.onchargingchange = async () => {
if (battery.charging) {
console.log('[debug]:', 'Connected to power adapter!');
if (notification_exist) {
chrome.notifications.clear(notification_id);
notification_exist = notification_showed = false;
}
}
}
battery.onlevelchange = async () => {
const battery_percentage = parseInt( (battery.level * 100).toFixed(0) ),
triggerLevel = await getKeyFromStorage('triggerLevel'),
enable_warning = await getKeyFromStorage('warning'),
warning_triggerLevel = await getKeyFromStorage('warning_triggerLevel');
console.log('[debug]:', 'Battery level changed:', `${battery_percentage}%`);
if ( ! battery.charging ) {
// show notification only if do_not_show_notification_again is not specified or the notification never shows before
if ( ( !(do_not_show_notification_again) || !(notification_showed) ) && battery_percentage <= triggerLevel ) {
const notification_options = {
type: 'basic',
iconUrl: 'icon.png',
title: 'Battery',
message: `${battery_percentage}% remaining`,
priority: 1
};
// check if any existing battery level notification
if ( ! notification_exist ) {
// create a new notification if not exist
chrome.notifications.create(notification_id, notification_options);
notification_exist = true
} else {
// update it if exists
chrome.notifications.update(notification_id, notification_options);
}
}
if ( enable_warning && battery_percentage == (warning_triggerLevel || triggerLevel) ) {
alert(`${battery_percentage}% remaining`);
}
}
}
chrome.notifications.onClosed.addListener((id, _) => {
console.log('[debug]:', 'Notification closed.');
notification_exist = false
});
})();