-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbackground.js
More file actions
68 lines (61 loc) · 1.73 KB
/
background.js
File metadata and controls
68 lines (61 loc) · 1.73 KB
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
import {
DEFAULT_BADGE_TEXT,
DEFAULT_COLOR,
FETCH_RESULT_URL,
getBrowserPolyfill,
setBadge,
setBadgeLocalStorage,
} from "../common.js";
let tabUrl = "";
const currentBrowser = getBrowserPolyfill();
async function updateBadge(ecoindexData) {
if (!ecoindexData["latest-result"].id) {
await setBadge(DEFAULT_COLOR, DEFAULT_BADGE_TEXT);
await setBadgeLocalStorage(tabUrl, DEFAULT_COLOR, DEFAULT_BADGE_TEXT);
} else {
const { color, grade: text } = ecoindexData["latest-result"];
setBadgeLocalStorage(tabUrl, color, text)
.then()
.catch(async () => {
await setBadge(DEFAULT_COLOR, DEFAULT_BADGE_TEXT);
});
await setBadge(color, text);
}
}
async function getBadgeInfo() {
currentBrowser.storage.local.get([tabUrl]).then(async (result) => {
if (tabUrl === "about:newtab") {
await setBadge("transparent", "");
return;
}
if (!result[tabUrl] || result[tabUrl]?.expirationTimestamp < Date.now()) {
await setBadge(DEFAULT_COLOR, DEFAULT_BADGE_TEXT);
fetch(FETCH_RESULT_URL(tabUrl))
.then((r) => r.json())
.then(updateBadge)
.catch(async () => {
await setBadge(DEFAULT_COLOR, DEFAULT_BADGE_TEXT);
await setBadgeLocalStorage(tabUrl, DEFAULT_COLOR, DEFAULT_BADGE_TEXT);
});
} else {
const { text, color } = result[tabUrl];
await setBadge(color, text);
}
});
}
currentBrowser.tabs.onUpdated.addListener(async (_tabId, changeInfo) => {
if (changeInfo.url !== undefined && changeInfo.url !== "") {
tabUrl = changeInfo.url;
}
if (changeInfo.status === "loading") {
await getBadgeInfo();
}
});
currentBrowser.tabs.onActivated.addListener(async () => {
const [tab] = await currentBrowser.tabs.query({
active: true,
currentWindow: true,
});
tabUrl = tab.url;
await getBadgeInfo();
});