forked from mdn/webextensions-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
89 lines (77 loc) · 2.28 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
/*
Default settings. If there is nothing in storage, use these values.
*/
var defaultSettings = {
since: "hour",
dataTypes: ["history", "downloads"]
};
/*
Generic error logger.
*/
function onError(e) {
console.error(e);
}
/*
On startup, check whether we have stored settings.
If we don't, then store the default settings.
*/
function checkStoredSettings(storedSettings) {
if (!storedSettings.since || !storedSettings.dataTypes) {
browser.storage.local.set(defaultSettings);
}
}
const gettingStoredSettings = browser.storage.local.get();
gettingStoredSettings.then(checkStoredSettings, onError);
/*
Forget browsing data, according to the settings passed in as storedSettings
or, if this is empty, according to the default settings.
*/
function forget(storedSettings) {
/*
Convert from a string to a time.
The string is one of: "hour", "day", "week", "forever".
The time is given in milliseconds since the epoch.
*/
function getSince(selectedSince) {
if (selectedSince === "forever") {
return 0;
}
const times = {
hour: () => { return 1000 * 60 * 60 },
day: () => { return 1000 * 60 * 60 * 24 },
week: () => { return 1000 * 60 * 60 * 24 * 7}
}
const sinceMilliseconds = times[selectedSince].call();
return Date.now() - sinceMilliseconds;
}
/*
Convert from an array of strings, representing data types,
to an object suitable for passing into browsingData.remove().
*/
function getTypes(selectedTypes) {
let dataTypes = {};
for (let item of selectedTypes) {
dataTypes[item] = true;
}
return dataTypes;
}
const since = getSince(storedSettings.since);
const dataTypes = getTypes(storedSettings.dataTypes);
function notify() {
let dataTypesString = Object.keys(dataTypes).join(", ");
let sinceString = new Date(since).toLocaleString();
browser.notifications.create({
"type": "basic",
"title": "Removed browsing data",
"message": `Removed ${dataTypesString}\nsince ${sinceString}`
});
}
browser.browsingData.remove({since}, dataTypes).then(notify);
}
/*
On click, fetch stored settings and forget browsing data.
*/
browser.browserAction.onClicked.addListener(() => {
const gettingStoredSettings = browser.storage.local.get();
gettingStoredSettings.then(forget, onError);
});