0

I'm making a chrome extension to adapt the colors of the youtube website to the browser colors, and I am getting stuck on the CSSStyleSheet of the website. This is the function I have at this moment, sorry if its completely wrong, this is 4 different tutorials mashed together

async function getColorVariables() {
  const colorVariables = {};
  const response = await fetch('https://www.youtube.com/s/desktop/7fca68b5/cssbin/www-main-desktop-watch-page-skeleton.css');
  const stylesheet = await response.text();
  alert(stylesheet);
  // Get all style sheets
  const ruleList = stylesheet.cssStyleSheet;
  for (let j = 0; j < ruleList.length; j++) {
    const rule = ruleList[j];
    alert(rule.cssText);
    const variables = rule.cssVariables;
    for (let k = 0; k < variables.length; k++) {
      const variable = variables[k];
      alert(variable.value + " : " + variable.name);
      // Check if the variable is a color
      if (variable.value.startsWith('#') || variable.value.startsWith('rgb') || variable.value.startsWith('hsl')) {
        colorVariables[variable.name] = variable.value;
      }
    }
  }

  return colorVariables;
}

I am pretty sure this would be the right style sheet for what I am trying to do, but when I run this function, the alert(rule.cssText) returns undefined which stops the rest of the function from running. Any help would be greatly appreciated!

  • Are you sure you have the right stylesheet. Looking at it through an editor the only colors seem to be in radial-gradients (as rgba, none I could find as #s). – A Haworth Jun 19 '23 at 07:33

1 Answers1

0

For obtaining the CSSStyleSheet object, I think you should be using document.styleSheets rather than doing a web request.

Once you have the CSSStyleSheet object, surely you need to use the cssRules property before you start iterating through each rule. As per this example:

const ruleList = document.styleSheets[0].cssRules;
for (let i = 0; i < ruleList.length; i++) {
  console.log(ruleList[i]);
}
Brett Donald
  • 6,745
  • 4
  • 23
  • 51
  • it gets the stylesheet from my popup, not the website I'm trying to alter, so I tried the web request because of that – Oliemanq Jun 19 '23 at 16:37