This repository has been archived by the owner on Sep 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoptions.js
109 lines (78 loc) · 2.55 KB
/
options.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// chrome.storage.local.clear(['options']);
var $form = document.querySelector('form');
getOptions();
document.querySelector('.copyright span.extension-version').innerHTML = chrome.runtime.getManifest().version;
$form.addEventListener('submit', function(e){
e.preventDefault();
var $button = this.querySelector('button[type=submit]');
var datas = new FormData($form);
options = serialize(datas);
chrome.storage.local.set({'options': options});
chrome.storage.local.remove(['refreshStepIndex']);
$button.innerHTML = 'Saved';
$notif = document.querySelector('.saved-notif');
$notif.classList.add('show');
setTimeout(function(){
$button.innerHTML = 'Save';
}, 1000);
setTimeout(function(){
$notif.classList.remove('show');
$notif.classList.add('hide');
setTimeout(function(){
$notif.classList.remove('hide');
}, 1000);
}, 3000);
});
$form.querySelector('.btn-reset').addEventListener('click', function(e){
e.preventDefault();
chrome.storage.local.remove(['options', 'refreshStepIndex']);
location.reload();
});
function getOptions(){
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function(){
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
var defaultOptions = JSON.parse(httpRequest.response);
chrome.storage.local.get('options', (data) => {
var savedOptions;
if(data.options != undefined){
savedOptions = data.options;
} else {
savedOptions = {};
}
var mergedOptions = { ...defaultOptions, ...savedOptions };
populateForm($form, mergedOptions);
});
}
}
};
httpRequest.open('GET', './defaultOptions.json');
httpRequest.send();
}
function populateForm($form, options){
for (const [key, value] of Object.entries(options)) {
var $element = $form.querySelector('#'+key);
$element.value = value;
}
}
/*!
* Serialize all form data into an object
* (c) 2021 Chris Ferdinandi, MIT License, https://gomakethings.com
* @param {FormData} data The FormData object to serialize
* @return {String} The serialized form data
*/
function serialize (data) {
let obj = {};
for (let [key, value] of data) {
if (obj[key] !== undefined) {
if (!Array.isArray(obj[key])) {
obj[key] = [obj[key]];
}
obj[key].push(value);
} else {
obj[key] = value;
}
}
return obj;
}