Detect if the browser is using dark mode and use a different favicon

后端 未结 4 820
不思量自难忘°
不思量自难忘° 2021-01-30 08:33

Google Chrome 73 has been released, and it adds \"dark mode\" support to the browser. I notice that a lot of favicons look bad now.

Is there a way to d

4条回答
  •  情歌与酒
    2021-01-30 09:33

    The easiest option is to change the source when you change the mode on your computer.

    var element = document.querySelector("link[rel='icon']");
    const darkModeListener = (event) => {
    if (event.matches) {
      console.log("dark");
      element.setAttribute("href","img/favicon-dark.svg");
    } else {
      console.log("light");
      element.setAttribute("href","img/favicon-light.svg");
    }
    };
    
    // Update favicon on Mode change 
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', darkModeListener);
    
    // Check Mode on load
    if (window.matchMedia && window.matchMedia('(prefers-color-scheme:      dark)').matches) {
      element.setAttribute("href","img/favicon-dark.svg");
    } else {
      element.setAttribute("href","img/favicon-light.svg");
    }
     

    But if you have a multi-device favicon then you need to do something like this ...

    // Switch Favicon on Dark/Light Mode
            let colorSchemeQueryList = window.matchMedia('(prefers-color-scheme: dark)');
                const setColorScheme = e => {
                  if (e.matches) {
                    // Dark
                    var favicon = document.querySelectorAll('link[data-type="favicon"]');
                    var i = favicon.length;
                    while (i--) {              
                      favicon[i].setAttribute('href', favicon[i].dataset.dark);
                    }
                  } else {
                    // Light
                    var favicon = document.querySelectorAll('link[data-type="favicon"]');
                    var i = favicon.length;
                    while (i--) {              
                      favicon[i].setAttribute("href", favicon[i].dataset.light);
                    }
                  }
                }
               
               setColorScheme(colorSchemeQueryList);
               colorSchemeQueryList.addListener(setColorScheme);
    
      
      
      
      

提交回复
热议问题