← Pablo Murad

Snippets

A small script to pull a site's CSS variables

A small piece of JavaScript I wrote: paste it in the browser's developer console and it collects a site's CSS variables, classes, IDs and the rules for colors, fonts and spacing, then downloads everything as a JSON file.

I wrote a small piece of JavaScript that reads a website's CSS and hands back what it's made of: the CSS variables (the --something custom properties) with their values, the classes and IDs on the page, and every rule that sets colors, fonts, borders or spacing.

Using it takes three steps:

  1. Open the site you want to look at.
  2. Open the developer console. F12 works in most browsers, or Ctrl+Shift+J in Chrome (Cmd+Option+J on a Mac).
  3. Paste the script and press Enter.1

It downloads a file called site-name-css-audit.json and prints a short summary in the console.

a-small-script-to-pull-a-sites-css-variables.js raw
(() => {
    const variables = new Set();
    const rules = [];
    const inaccessible = [];
    const visited = new Set();

    function scanSheet(sheet) {
        if (!sheet || visited.has(sheet)) return;
        visited.add(sheet);

        try {
            scanRules(sheet.cssRules);
        } catch {
            inaccessible.push(
                sheet.href?.split("?")[0] || "inline"
            );
        }
    }

    function scanRules(list) {
        for (const rule of list) {
            if (rule.style && rule.selectorText) {
                const properties = {};

                for (const name of Array.from(rule.style)) {
                    const value = rule.style
                        .getPropertyValue(name).trim();

                    if (name.startsWith("--")) {
                        variables.add(name);
                    }

                    for (const match of value.matchAll(
                        /var\(\s*(--[\w-]+)/g
                    )) {
                        variables.add(match[1]);
                    }

                    if (
                        name.startsWith("--") ||
                        /^(color|background|border|font|padding|margin|gap|box-shadow|line-height|letter-spacing)/.test(name)
                    ) {
                        if (!/url\s*\(/i.test(value)) {
                            properties[name] = value;
                        }
                    }
                }

                if (Object.keys(properties).length) {
                    rules.push({
                        selector: rule.selectorText,
                        properties
                    });
                }
            }

            if (rule.styleSheet) {
                scanSheet(rule.styleSheet);
            } else if (rule.cssRules) {
                scanRules(rule.cssRules);
            }
        }
    }

    Array.from(document.styleSheets).forEach(scanSheet);

    function getVariables(element) {
        const style = getComputedStyle(element);

        return Object.fromEntries(
            [...variables].sort()
                .map(name => [
                    name,
                    style.getPropertyValue(name).trim()
                ])
                .filter(([, value]) =>
                    value && !/url\s*\(/i.test(value))
        );
    }

    const data = {
        rootVariables: getVariables(document.documentElement),
        bodyVariables: getVariables(document.body),
        classes: [...new Set(
            Array.from(document.querySelectorAll("[class]"))
                .flatMap(el => Array.from(el.classList))
        )].sort(),
        ids: [...new Set(
            Array.from(document.querySelectorAll("[id]"))
                .map(el => el.id)
        )].sort(),
        rules,
        inaccessible
    };

    const blob = new Blob(
        [JSON.stringify(data, null, 2)],
        { type: "application/json" }
    );

    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");

    link.href = url;
    link.download = `${location.hostname}-css-audit.json`;
    link.click();

    setTimeout(() => URL.revokeObjectURL(url), 1000);

    console.log("Audit finished:", {
        variables: variables.size,
        rules: rules.length,
        classes: data.classes.length,
        ids: data.ids.length
    });
})();

curl -O https://pablomurad.com/snippets/a-small-script-to-pull-a-sites-css-variables.js

Run on this blog, it found 20 variables, 529 rules, 48 classes and a single ID. The variables come with the values the browser is really using, so the palette, the fonts and the spacing of the whole site show up in a few lines:

The start of the JSON file the script downloads, opened in Chrome. Under "rootVariables" it lists the CSS variables of pablomurad.com with their values: --code-bg #18161d, --code-ink #e6e1d6, --gap 2rem, --gutter 2.5rem, --hand with the Caveat font stack, --ink #111, --line #e6e6e6, --mono with the IBM Plex Mono stack, --muted #666, --page 55rem, --paper #fff, --paper-2 #f4f4f2, --rail 8.5rem, --rule #c8c8c8, --signal #d93a2b and --text with the Source Serif 4 stack.
The top of the file it made for this very site.

One limit: stylesheets loaded from another domain can't always be read by scripts on the page2. When that happens, the script lists their addresses under inaccessible instead of failing, so it's clear what was left out. Image URLs are skipped on purpose too, to keep the file small and readable.

I hope it's useful to someone.

Notes

  1. The first time, Chrome and Firefox may refuse the paste and ask for "allow pasting" to be typed. It's a guard against people being tricked into running code they don't understand, so it's worth reading any script before pasting it, this one included. ↩

  2. Browsers block reading the rules of a stylesheet from another origin unless that server allows it with CORS headers. It's a security rule, and the script catches the error and moves on. ↩

Reply by email

Comments

Leave a comment

Comments are read before they show up here. No email address needed.