-1

I am making a chrome extension that mimics googles material you color schemes but on googles websites, starting with youtube. Whenever I try to use querySelector on :root and it just gets the root of my popup.html file. I've tried to do a web request but that didn't work. This is my first real coding project outside of my schools java class, so I am still learning js, html, and css as I go.

I am kind of at a loss for what else I could try, as any forums that I find just tell me to use querySelector, so they aren't much help. If anyone has a solution to this, I would greatly appreciate the help!

  • Please provide a code example of what you have tried to help better diagnose your issue. It will also help others provide feedback and help you learn. – Peter Meadley Aug 04 '23 at 17:58

1 Answers1

0

Alright look at this:

Define a content script: In your manifest.json file, specify the content script to be injected into the webpage. Content scripts should include a JavaScript file (let's call it contentScript.js) where you can perform actions on the webpage.

{
  "manifest_version": 2,
  "name": "Your Extension Name",
  "version": "1.0",
  "content_scripts": [
    {
      "matches": ["*://*.youtube.com/*"], // Match the websites where you want to access CSS variables
      "js": ["contentScript.js"]
    }
  ],
  "browser_action": {
    "default_popup": "popup.html"
  }
}

contentScript.js: This script will run on the matched websites. In this script, you can use the window.getComputedStyle() function to access CSS variables. You'll need to inject this script into the webpage using the executeScript method in your background script.

// contentScript.js
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  if (request.message === "getCSSVariables") {
    const rootStyles = window.getComputedStyle(document.documentElement);
    const cssVariableValue = rootStyles.getPropertyValue('--your-css-variable-name');
    sendResponse({ cssVariableValue });
  }
});

popup.html: In your popup.html, you can use chrome.tabs to communicate with the content script and get the CSS variable value.

<!-- popup.html -->
<!DOCTYPE html>
<html>
<head>
  <title>Your Extension Popup</title>
</head>
<body>
  <button id="getVariableButton">Get CSS Variable Value</button>
  <div id="result"></div>

  <script src="popup.js"></script>
</body>
</html>

popup.js: In this script, you can add a click event listener to the button and use chrome.tabs.sendMessage to communicate with the content script and get the CSS variable value.

// popup.js
document.getElementById("getVariableButton").addEventListener("click", function () {
  chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
    chrome.tabs.sendMessage(tabs[0].id, { message: "getCSSVariables" }, function (response) {
      document.getElementById("result").textContent = response.cssVariableValue;
    });
  });
});

Give it a look ;)