import { DEFAULT_POLL_INTERVAL, fetchNotificationCount, getNotificationsUrl, getNotificationsUrlPattern, } from "@/utils/api"; import { renderCount, renderError } from "@/utils/badge"; import { notificationCount } from "@/utils/storage"; const scheduleNextPoll = (intervalSeconds: number): void => { browser.alarms.clear("poll"); browser.alarms.create("poll", { delayInMinutes: Math.max(intervalSeconds / 60, 1), }); }; const updateCount = async (): Promise => { try { const { count, pollInterval } = await fetchNotificationCount(); await notificationCount.setValue(count); renderCount(count); scheduleNextPoll(pollInterval); } catch { renderError(); scheduleNextPoll(DEFAULT_POLL_INTERVAL); } }; export default defineBackground(() => { const action = browser.action ?? browser.browserAction; browser.alarms.onAlarm.addListener((alarm) => { if (alarm.name === "poll") updateCount(); }); action.onClicked.addListener(async () => { const tabs = await browser.tabs.query({ currentWindow: true, url: getNotificationsUrlPattern(), }); if (tabs[0]?.id) { browser.tabs.update(tabs[0].id, { active: true }); browser.tabs.reload(tabs[0].id); } else { browser.tabs.create({ url: getNotificationsUrl() }); } setTimeout(updateCount, 2000); }); updateCount(); });