summaryrefslogtreecommitdiff
path: root/content-script.js
blob: 4e99e297583445f5ac47b2fdd06a48a1ff879ff9 (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
(function () {
  const stylesheetId = "zeninternet-custom-styles";

  // Create or get our stylesheet element
  function getStylesheet() {
    let stylesheet = document.getElementById(stylesheetId);
    if (!stylesheet) {
      stylesheet = document.createElement("style");
      stylesheet.id = stylesheetId;
      stylesheet.type = "text/css";
      document.head.appendChild(stylesheet);
    }
    return stylesheet;
  }

  // Update our stylesheet content
  function updateStyles(css) {
    const stylesheet = getStylesheet();
    stylesheet.textContent = css || "";
    console.log("ZenInternet: Styles were " + (css ? "updated" : "removed"));
  }

  // Announce content script is ready and provide current hostname
  function announceReady() {
    try {
      browser.runtime
        .sendMessage({
          action: "contentScriptReady",
          hostname: window.location.hostname,
        })
        .catch((err) => {
          // Silent fail - background might not be ready yet
          console.log("ZenInternet: Could not announce ready state");
        });
    } catch (e) {
      // Fail silently
    }
  }

  // Listen for messages from background script
  browser.runtime.onMessage.addListener((message) => {
    if (message.action === "applyStyles") {
      updateStyles(message.css);
      return Promise.resolve({ success: true });
    }
    return false;
  });

  // Announce content script is ready on load
  announceReady();
})();