-
Notifications
You must be signed in to change notification settings - Fork 1
/
background.js
123 lines (100 loc) · 3.21 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
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
let db; // Define db variable globally
// Define defaultValues here
let defaultValues = [
{
name: "switchValue",
value: true,
},
{
name: "numDarkPatternIdentified",
value: 0,
},
{
name: "darkPatternIdentified",
value: null,
},
{
name: "textComparison",
value: null,
},
];
// Define insertValue function
function insertValue(values) {
if (db) {
const insertTransaction = db.transaction("utils", "readwrite");
const objectStore = insertTransaction.objectStore("utils");
return new Promise((resolve, reject) => {
insertTransaction.oncomplete = function () {
console.log("[COMPLETE] Insertion transactions completed");
resolve(true);
};
insertTransaction.onerror = function () {
console.log("[ERROR] Default values already present");
resolve(false);
};
values.forEach((util) => {
let request = objectStore.add(util);
request.onsuccess = function () {
console.log("[SUCCESS] Added " + util.name + " " + util.value);
};
});
});
}
}
// Define retrieveValue function
function retrieveValue(name) {
const retrieveTransaction = db.transaction("utils", "readonly");
const objectStore = retrieveTransaction.objectStore("utils");
return new Promise((resolve, reject) => {
retrieveTransaction.oncomplete = function () {
console.log("[COMPLETE] Retrieve transaction completed");
};
retrieveTransaction.onerror = function () {
console.log("[ERROR] Problem in retrieval");
};
let request = objectStore.get(name);
request.onsuccess = function (event) {
resolve(event.target.result);
};
});
}
// Define createDB function
function createDB() {
return new Promise((resolve, reject) => {
const request = self.indexedDB.open("UtilsDB", 1);
request.onerror = function (event) {
console.log("[ERROR] Failed to open Database");
reject();
};
request.onupgradeneeded = function (event) {
db = event.target.result;
let objectStore = db.createObjectStore("utils", {
keyPath: "name",
});
objectStore.transaction.oncomplete = function (event) {
console.log("[COMPLETE] ObjectStore created");
resolve();
};
};
request.onsuccess = function (event) {
db = event.target.result;
console.log("[SUCCESS] Database opened successfully");
insertValue(defaultValues).then(() => {
resolve();
}).catch(() => {
reject();
});
db.onerror = function (event) {
console.log("[ERROR] Failed to open Database");
reject();
};
};
});
}
// Rest of your code
// Call createDB
createDB().then(() => {
// Database is initialized, you can perform operations here
}).catch(() => {
console.log("Error creating database");
});