summaryrefslogtreecommitdiff
path: root/inject-css.js
blob: 88ddacc05847cf63e6558982067f45771450780f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
let logging = false;

if (logging) console.log("inject-css.js script loaded");

(async () => {
  try {
    const settings = await browser.storage.local.get("transparentZenSettings");
    if (logging) console.log("Settings loaded", settings);

    if (!settings.transparentZenSettings?.enableStyling) {
      if (logging) console.log("Styling is disabled");
      return;
    }

    if (logging) console.log("Styling is enabled");
    const data = await browser.storage.local.get("styles");
    if (logging) console.log("Styles data loaded", data);

    const currentUrl = window.location.hostname;
    if (logging) console.log("Current URL hostname", currentUrl);

    let cssFileName = Object.keys(data.styles?.website || {}).find((key) => {
      const siteName = key.replace(".css", "");
      if (siteName.startsWith("+")) {
        const baseSiteName = siteName.slice(1);
        return currentUrl.endsWith(baseSiteName);
      }
      return currentUrl === siteName || currentUrl === `www.${siteName}`;
    });

    if (!cssFileName && settings.transparentZenSettings?.forceStyling) {
      cssFileName = "example.com.css";
    }

    if (!cssFileName) {
      if (logging) console.log("No CSS file found for current site");
      return;
    }

    if (logging) console.log("CSS file found for current site", cssFileName);

    const features = data.styles.website[cssFileName];
    const siteKey = `transparentZenSettings.${currentUrl}`;
    const siteData = await browser.storage.local.get(siteKey);
    const featureSettings = siteData[siteKey] || {};

    let combinedCSS = "";
    for (const [feature, css] of Object.entries(features)) {
      if (featureSettings[feature] !== false) {
        combinedCSS += css + "\n";
      }
    }

    if (combinedCSS) {
      const style = document.createElement("style");
      style.textContent = combinedCSS;
      document.head.appendChild(style);
      if (logging) console.log(`Injected custom CSS for ${currentUrl}`);
    }
  } catch (error) {
    console.error("Error injecting CSS:", error);
  }
})();