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