summaryrefslogtreecommitdiffstats
path: root/background.js
diff options
context:
space:
mode:
authorLeonardo Bishop <me@leonardobishop.net>2025-09-17 20:14:09 +0100
committerLeonardo Bishop <me@leonardobishop.net>2025-09-17 20:14:09 +0100
commit61e27eef33da20a9f174d2debee151cb8b100389 (patch)
tree454fcbe8fdac7c9e306a7df3c7bcaa907eb5a65f /background.js
Initial commit
Diffstat (limited to 'background.js')
-rw-r--r--background.js84
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);
+ }
+});