Tangled notifications browser extension
1import {
2 fetchNotificationCount,
3 getNotificationsUrl,
4 getNotificationsUrlPattern,
5} from "@/utils/api";
6import { renderCount, renderError } from "@/utils/badge";
7import { notificationCount } from "@/utils/storage";
8
9const POLL_INTERVAL_MINUTES = 1;
10
11const updateCount = async (): Promise<void> => {
12 try {
13 const count = await fetchNotificationCount();
14 await notificationCount.setValue(count);
15 renderCount(count);
16 } catch {
17 renderError();
18 }
19};
20
21export default defineBackground(() => {
22 const action = browser.action ?? browser.browserAction;
23
24 browser.alarms.create("poll", { periodInMinutes: POLL_INTERVAL_MINUTES });
25 browser.alarms.onAlarm.addListener(() => updateCount());
26
27 action.onClicked.addListener(async () => {
28 const tabs = await browser.tabs.query({
29 currentWindow: true,
30 url: getNotificationsUrlPattern(),
31 });
32
33 if (tabs[0]?.id) {
34 browser.tabs.update(tabs[0].id, { active: true });
35 browser.tabs.reload(tabs[0].id);
36 } else {
37 browser.tabs.create({ url: getNotificationsUrl() });
38 }
39
40 setTimeout(updateCount, 2000);
41 });
42
43 updateCount();
44});