CSSカスタムプロパティを変更するUserScript
テーブル記法で書かれたCSSカスタムプロパティ(CSS変数)をセットする(変更する)UserScriptです。
テーブルの書式は
table:sample-list
カスタムプロパティ プロパティ値 コメント
--body-bg #202228 全体の背景色
1カラム目がCSS カスタムプロパティの名前、2カラム目がCSS カスタムプロパティの値です
3カラム目以降は無視されます
APIからアクセスするので、テーブルを記述するプロジェクトは公開プロジェクトでないといけません。
設定の仕方
テーブル記法でカスタムプロパティを記述します
API の からテーブルのアクセス確認
自分のページのscript.jsに追加
code:sample-script.js
import { loadAndSetCssVariables } from "/api/code/villagepump/CSSカスタムプロパティを変更するUserScript/script.js";
loadAndSetCssVariables("/api/table/villagepump/suto3/property-list.csv");
loadAndSetCssVariables()で渡す引数はテーブル記法のURLです。
code:script.js
// script.js
/**
* Fetches a CSV file and sets its contents as CSS variables on the root element.
* Column 1 is used as the variable name (prefixed with --), and Column 2 as the value.
* @param {string} url - The URL of the CSV file to fetch.
*/
export const loadAndSetCssVariables = async (url) => {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(Network response was not ok: ${response.statusText});
}
const text = await response.text();
const lines = text.split("\n");
// Remove header and process lines
lines.slice(1).forEach(line => {
if (!line.trim()) {
return; // Skip empty lines
}
const columns = line.split(",");
if (columns.length >= 2) {
// Sanitize name for CSS variable format (e.g., remove invalid characters)
let name = --${columns[0].trim().replace(/[^a-zA-Z0-9-]/g, "-")};
// Coalesce 3 or more hyphens at the start into 2
name = name.replace(/^-{3,}/g, "--");
const value = columns1.trim().replace(/\\\/g, ""); // Clean value like url
if (name !== "--") {
document.documentElement.style.setProperty(name, value);
console.log(Set CSS variable: ${name} = ${value});
}
}
});
} catch (error) {
console.error("Failed to load or set CSS variables:", error);
// Re-throw the error to allow the caller to handle it if needed
throw error;
}
};
UserScript.icon
#井戸端アドベントカレンダー2025