javascriptfaviconmacos-darkmode

Dark & Light Mode: How to switch manifest and favicon?


The manifest and the favicon are dependent on the light/darkmode is there any way of changing them as the user changes the mode in the operating system?

Ive got the event listener firing

  window.matchMedia('(prefers-color-scheme: dark)').addEventListener( "change", (e) => {
    if (e.matches) console.log('your in dark mode);
  });

but the manifest is loaded from the react public folder..

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="logo192.png" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <title>My Site</title>
  </head>
  <body>
    <noscript>Please enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>

Not sure how to handle the favicon that is also in the root of the public folder. Also the meta tag for theme-color would need to change.


Solution

  • Using the suggestion from @kishore I've managed to get the favicon working, I'm sure someone better can tighten up my code but it works, in the html I added an id...

    <link rel="shortcut icon" id='favicon' href="%PUBLIC_URL%/favicon.ico" />
    <link rel="manifest" id='manifest' href="%PUBLIC_URL%/manifest.json" />
    

    then in the head section I added...

        <script>
          const usesDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
          const favicon = document.getElementById('favicon');
          const manifest = document.getElementById('manifest');
    
          function switchIcon(usesDarkMode) {
            if (usesDarkMode) { 
              favicon.href = '%PUBLIC_URL%/favicon-dark.ico';
              manifest.href='%PUBLIC_URL%/manifest-dark.json' 
            } else {
            favicon.href = '%PUBLIC_URL%/favicon-light.ico';
            manifest.href='%PUBLIC_URL%/manifest-light.json' 
            }
          }
    
          window.matchMedia('(prefers-color-scheme: dark)').addEventListener( "change", (e) => switchIcon(e.matches));
          switchIcon(usesDarkMode);
        </script>