-
Notifications
You must be signed in to change notification settings - Fork 0
/
popup.js
68 lines (58 loc) · 1.78 KB
/
popup.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
const SETTINGS_KEY = 'settings';
const SETTING_NAMES = [
'monthlyIncome',
'weeklyWorkdays',
'dailyWorkHours',
'dailyCommuteMinutes',
'monthlyCommuteCost',
'vacationDays',
'onOffSwitch'
];
function isCheckbox(element) {
return element.type === 'checkbox';
}
function getSettingValue(settingName) {
const element = document.getElementById(settingName);
if (isCheckbox(element)) {
return element.checked;
}
return Number(element.value);
}
function setSettingValue(settingName, value) {
const element = document.getElementById(settingName);
if (isCheckbox(element)) {
element.checked = value;
} else {
element.value = value;
}
}
function gatherSettings() {
return SETTING_NAMES.reduce((settings, name) => {
settings[name] = getSettingValue(name);
return settings;
}, {});
}
function saveSettingsToStorage(settings) {
browser.storage.local.set({ [SETTINGS_KEY]: settings }, notifyContentScript);
}
function notifyContentScript() {
browser.tabs.query({ active: true, currentWindow: true }, tabs => {
browser.tabs.sendMessage(tabs[0].id, { action: "settingsUpdated" });
});
}
function applyStoredSettingsToPage() {
browser.storage.local.get(SETTINGS_KEY, data => {
if (data[SETTINGS_KEY]) {
Object.keys(data[SETTINGS_KEY]).forEach(name => {
setSettingValue(name, data[SETTINGS_KEY][name]);
});
}
});
}
document.getElementById('settingsForm').addEventListener('submit', function(event) {
// Prevent the form from actually submitting
event.preventDefault();
const settings = gatherSettings();
saveSettingsToStorage(settings);
});
document.addEventListener('DOMContentLoaded', applyStoredSettingsToPage);