diff options
Diffstat (limited to 'background.js')
| -rw-r--r-- | background.js | 84 |
1 files changed, 84 insertions, 0 deletions
diff --git a/background.js b/background.js new file mode 100644 index 0000000..0f6a3a9 --- /dev/null +++ b/background.js @@ -0,0 +1,84 @@ +import { setIcon } from "./util.js"; + +let urls = new Set(); +let lastUrlsUpdateTime = 0; +let updating = false; + +function updateUrls() { + return browser.storage.local + .get(["apiUrl", "authToken"]) + .then(async ({ apiUrl, authToken }) => { + if (!apiUrl) { + console.warn("API URL not configured."); + setIcon(tabId, "default"); + return; + } + + await fetch(`${apiUrl}/entry`, { + headers: { + Authorization: authToken ? `Bearer ${authToken}` : undefined, + }, + }) + .then((response) => response.json()) + .then((data) => { + urls = new Set(data.data); + lastUrlsUpdateTime = Date.now(); + }) + .catch((error) => { + console.error(error); + }); + }); +} + +async function handleTabUpdate(tabId, url) { + setIcon(tabId, "wait"); + + if (updating) { + return; + } + + if (Date.now() - lastUrlsUpdateTime > 10 * 60 * 1000) { + updating = true; + await updateUrls(); + updating = false; + } + + if (urls.has(url)) { + setIcon(tabId, "saved"); + } else { + setIcon(tabId, "ready"); + } +} + +browser.tabs.onActivated.addListener(async (activeInfo) => { + const tab = await browser.tabs.get(activeInfo.tabId); + if (tab.url && tab.url.startsWith("http")) { + handleTabUpdate(tab.id, tab.url); + } +}); + +browser.tabs.onUpdated.addListener((tabId, changeInfo, tab) => { + if ( + changeInfo.status === "loading" && + tab.active && + tab.url?.startsWith("http") + ) { + setIcon(tabId, "wait"); + } + + if ( + changeInfo.status === "complete" && + tab.active && + tab.url?.startsWith("http") + ) { + handleTabUpdate(tabId, tab.url); + } +}); + +browser.runtime.onMessage.addListener(function (request, sender, sendResponse) { + if (request.action === "addSavedUrl") { + urls.add(request.data.url); + } else if (request.action === "removeSavedUrl") { + urls.delete(request.data.url); + } +}); |
