Here's a JavaScript program that dynamically changes a webpage's theme to a dark mode variant. The script processes all CSS rules in the page's stylesheets and inline styles on elements. It calculates colors on the fly by adjusting light background colors to their darker variants and dark text colors to their lighter variants, preserving the color identity.
(function() {
// List of CSS properties that typically contain colors
var colorProperties = [
'background',
'background-color',
'border-color',
'border-top-color',
'border-right-color',
'border-bottom-color',
'border-left-color',
'color',
'outline-color',
'text-decoration-color',
'fill',
'stroke'
];
// Function to check if a property is a color property
function isColorProperty(propName) {
return colorProperties.includes(propName);
}
// Function to determine if a color is light based on HSL lightness
function isLightColor(r, g, b) {
var hsl = rgbToHsl(r, g, b);
return hsl.l > 0.7;
}
// Adjusts the lightness of a color
function adjustLightness(r, g, b, deltaL) {
var hsl = rgbToHsl(r, g, b);
hsl.l += deltaL;
hsl.l = Math.max(0, Math.min(1, hsl.l)); // Clamp between 0 and 1
var rgb = hslToRgb(hsl.h, hsl.s, hsl.l);
return rgb;
}
// Converts RGB to HSL
function rgbToHsl(r, g, b) {
r /= 255; g /= 255; b /= 255;
var max = Math.max(r, g, b), min = Math.min(r, g, b);
var h, s, l = (max + min) / 2;
if (max === min) {
h = s = 0; // Achromatic
} else {
var d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r:
h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
break;
case g:
h = ((b - r) / d + 2) / 6;
break;
case b:
h = ((r - g) / d + 4) / 6;
break;
}
}
return { h: h, s: s, l: l };
}
// Converts HSL to RGB
function hslToRgb(h, s, l) {
var r, g, b;
if (s === 0) {
r = g = b = l; // Achromatic
} else {
var hue2rgb = function(p, q, t) {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1/6) return p + (q - p) * 6 * t;
if (t < 1/2) return q;
if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;
return p;
};
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hue2rgb(p, q, h + 1/3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1/3);
}
return {
r: Math.round(r * 255),
g: Math.round(g * 255),
b: Math.round(b * 255)
};
}
// Parses a color string and returns an RGB object
function parseColor(colorStr) {
var ctx = document.createElement('canvas').getContext('2d');
ctx.fillStyle = colorStr;
var computedColor = ctx.fillStyle;
// Match rgb or rgba string
var rgbaRegex = /^rgba?\((\d+),\s*(\d+),\s*(\d+)/;
var match = rgbaRegex.exec(computedColor);
if (match) {
return {
r: parseInt(match[1]),
g: parseInt(match[2]),
b: parseInt(match[3])
};
}
// Match hex color code
var hexRegex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i;
match = hexRegex.exec(computedColor);
if (match) {
var hex = match[1];
if (hex.length === 3) {
hex = hex.split('').map(function(h) {
return h + h;
}).join('');
}
var intVal = parseInt(hex, 16);
return {
r: (intVal >> 16) & 255,
g: (intVal >> 8) & 255,
b: intVal & 255
};
}
return null;
}
// Converts RGB object to CSS color string
function rgbToString(r, g, b) {
return 'rgb(' + r + ', ' + g + ', ' + b + ')';
}
// Checks if the property is a background property
function isBackgroundProperty(propName) {
return propName.startsWith('background');
}
// Checks if the property is a text color property
function isTextColorProperty(propName) {
return propName === 'color';
}
// Adjusts the color based on the property
function adjustColor(color, propName) {
if (isBackgroundProperty(propName)) {
if (isLightColor(color.r, color.g, color.b)) {
// Darken light backgrounds
var adjusted = adjustLightness(color.r, color.g, color.b, -0.3);
return adjusted;
}
} else if (isTextColorProperty(propName)) {
if (!isLightColor(color.r, color.g, color.b)) {
// Lighten dark text
var adjusted = adjustLightness(color.r, color.g, color.b, 0.3);
return adjusted;
}
} else {
// For other color properties, adjust as needed
// This example darkens light colors and lightens dark colors
if (isLightColor(color.r, color.g, color.b)) {
var adjusted = adjustLightness(color.r, color.g, color.b, -0.3);
} else {
var adjusted = adjustLightness(color.r, color.g, color.b, 0.3);
}
return adjusted;
}
return color;
}
// Process all stylesheets
function processStylesheets() {
var styleSheets = document.styleSheets;
for (var i = 0; i < styleSheets.length; i++) {
var styleSheet = styleSheets[i];
// Ignore stylesheets we can't access (due to CORS)
try {
var cssRules = styleSheet.cssRules || styleSheet.rules;
} catch (e) {
continue;
}
if (!cssRules) continue;
for (var j = 0; j < cssRules.length; j++) {
var rule = cssRules[j];
if (rule.type === CSSRule.STYLE_RULE) {
var style = rule.style;
for (var k = 0; k < style.length; k++) {
var propName = style[k];
var propValue = style.getPropertyValue(propName);
if (isColorProperty(propName)) {
var color = parseColor(propValue);
if (color) {
var adjustedColor = adjustColor(color, propName);
var newColorStr = rgbToString(adjustedColor.r, adjustedColor.g, adjustedColor.b);
style.setProperty(propName, newColorStr, style.getPropertyPriority(propName));
}
}
}
} else if (rule.type === CSSRule.MEDIA_RULE || rule.type === CSSRule.SUPPORTS_RULE) {
// Handle @media and @supports rules recursively
processRuleList(rule.cssRules || rule.rules);
}
}
}
}
// Process a list of CSS rules (used for @media and @supports)
function processRuleList(ruleList) {
for (var j = 0; j < ruleList.length; j++) {
var rule = ruleList[j];
if (rule.type === CSSRule.STYLE_RULE) {
var style = rule.style;
for (var k = 0; k < style.length; k++) {
var propName = style[k];
var propValue = style.getPropertyValue(propName);
if (isColorProperty(propName)) {
var color = parseColor(propValue);
if (color) {
var adjustedColor = adjustColor(color, propName);
var newColorStr = rgbToString(adjustedColor.r, adjustedColor.g, adjustedColor.b);
style.setProperty(propName, newColorStr, style.getPropertyPriority(propName));
}
}
}
} else if (rule.type === CSSRule.MEDIA_RULE || rule.type === CSSRule.SUPPORTS_RULE) {
// Handle nested @media and @supports rules recursively
processRuleList(rule.cssRules || rule.rules);
}
}
}
// Process inline styles on elements
function processInlineStyles() {
var allElements = document.getElementsByTagName("*");
for (var i = 0; i < allElements.length; i++) {
var elem = allElements[i];
var style = elem.style;
for (var j = 0; j < style.length; j++) {
var propName = style[j];
var propValue = style.getPropertyValue(propName);
if (isColorProperty(propName)) {
var color = parseColor(propValue);
if (color) {
var adjustedColor = adjustColor(color, propName);
var newColorStr = rgbToString(adjustedColor.r, adjustedColor.g, adjustedColor.b);
style.setProperty(propName, newColorStr, style.getPropertyPriority(propName));
}
}
}
}
}
// Start processing
processStylesheets();
processInlineStyles();
})();
Explanation:
-
Color Adjustment Logic:
- The script identifies if a color is light or dark by converting RGB values to HSL and checking the lightness component.
- For light background colors, it reduces the lightness to make them darker.
- For dark text colors, it increases the lightness to make them lighter.
- This preserves the hue and saturation, maintaining the original color identity.
-
Parsing Colors:
- The
parseColor function uses a temporary canvas element to parse various color formats (named colors, hex codes, RGB, etc.).
- It extracts the RGB components which are used for adjustment.
-
Processing Styles:
- Stylesheets:
- Iterates through all stylesheets and their CSS rules.
- Adjusts color properties within each rule.
- Handles
@media and @supports rules recursively.
- Inline Styles:
- Iterates through all elements in the DOM.
- Adjusts color properties set via inline styles.
-
Color Properties:
- The script focuses on CSS properties commonly associated with colors, such as
background-color, color, border-color, etc.
Usage:
You can include this script in your webpage or execute it via the browser console to dynamically switch the theme to a dark mode variant.
<!-- Include the script at the end of your body or in a script tag -->
<script>
// Paste the entire JavaScript code here
</script>
Note:
- The script is designed to be comprehensive, but due to the complexity of CSS and the possibility of styles being applied via external stylesheets or dynamic styles, there might be cases where some colors are not adjusted.
- For stylesheets from different domains (cross-origin), the browser's security policies (CORS) may prevent access to their CSS rules. The script handles this by skipping such stylesheets.
- The thresholds and adjustment values (e.g.,
-0.3 for darkening) can be tweaked to achieve the desired visual result.
- This script does not handle background images, gradients, or complex CSS functions that involve colors.
Feel free to adapt and extend the script based on your specific needs.