Today, I encountered the same issue and was able to resolve it by implementing the following code upon page load. Initially, I tried to listen for print requests (assuming similar to your approach), but after some experimentation, I found that the "preferred-color-scheme" event triggers with a value of "light" when attempting to print. Additionally, I needed to monitor this event to capture user-initiated color scheme changes.
I'm curious to know if this solution works for you as well. I tested it on Edge, Chrome, Firefox, and a few other browsers. I'd be interested to learn if there are any different behaviors in other browsers that may cause this solution to fail.
(() =>
{
// Identifying the browser's preferred theme
function GetPreferredTheme()
{
// Default to light mode
var selected_theme = "light";
// Switch to dark theme if preferred by the browser
if (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches)
{
selected_theme = "dark";
}
return selected_theme;
};
// Setting the theme based on specified input or default to browser's preference
function SetTheme(theme = "")
{
if (theme.length == 0)
{
theme = GetPreferredTheme();
}
document.documentElement.setAttribute("data-bs-theme", theme);
};
// Scheme listener to detect when dark theme is selected
function SchemeListener(event)
{
event.matches ? SetTheme("dark") : SetTheme("light");
};
// If window.matchMedia is supported, add listener to toggle themes
if (window.matchMedia)
{
// Add listeners to switch themes when user changes settings
var scheme = window.matchMedia("(prefers-color-scheme: dark)");
if (scheme)
{
scheme.addEventListener("change", SchemeListener);
}
}
// Display content using the browser's preferred theme
SetTheme();
})();