139
Views
4
Comments
Get browser light/dark theme
Question

Hi everyone!

Is there any action in OS than can retrieve the browsers default theme? i.e light or dark mode? 

I know you can use: @media (prefers-color-scheme: dark) to apply a theme, but this is not (yet) available on all browsers and I wanted something that could also be used to modify the favicon, hence the server action...


2024-07-05 14-16-55
Daniël Kuhlmann
 
MVP

Hi,

Not an answer to your question but prefers-color-scheme is supported by al major browsers except IE.

See https://caniuse.com/#search=prefers-color-scheme

Regards,

Daniel

2020-12-07 17-12-41
J Grou

Daniël Kuhlmann wrote:

Hi,

Not an answer to your question but prefers-color-scheme is supported by al major browsers except IE.

See https://caniuse.com/#search=prefers-color-scheme

Regards,

Daniel

Yes you are correct, i saw a print from that same website, which obv hasnt been updated since its a static picture and therefore i got the wrong idea. Nonetheless, and like you said, I still need a way to use it as a server action method. 

I saw this line to use for JS: window.matchMedia('(prefers-color-scheme: dark)').matches

I havent had time to try it yet, but I reckon I could convert the output of that JS to an OS variable. Whats your opinion on that?


2024-07-05 14-16-55
Daniël Kuhlmann
 
MVP

For traditional web the rendering takes place on the server, so not sure you can achieve that without first have a page loaded in the browser, then doing another server call.

For reactive or mobile you can all do this client side.

UserImage.jpg
Terence Leung

If you are using traditional web, in the web screen, go to "advanced", then add JavaScript as follow:

var darkModeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');

function handleDarkmode(e){

//https://jross.me/updating-your-website-favicon-dynamically-with-dark-mode/

    var darkModeOn = e.matches; // true if dark mode is enabled

    var favicon = document.querySelector('link[rel="shortcut icon"]'); // get favicon-192.png element

    if(!favicon){

        return; 

    }

    // replace icons with dark/light themes as appropriate

    if(darkModeOn){

        favicon.href = '/xxxxx/favicon_dark.png';

    }else{

        favicon.href = '/xxxx/favicon.png';

    }

}

$(document).ready(

    function() {

        handleDarkmode(darkModeMediaQuery);

        darkModeMediaQuery.addListener(handleDarkmode);

    }

);

It works for Edge, but not Google Chrome, I don't know why.

Community GuidelinesBe kind and respectful, give credit to the original source of content, and search for duplicates before posting.