Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

javascript - JS change browser tab icon when darkmode is enabled

I have this script, that works for what its supposed to:

const darkModeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
  darkModeMediaQuery.addListener((e) => {
    const darkModeOn = e.matches;
    console.log(`Dark mode is ${darkModeOn ? '?? on' : '?? off'}.`);
  });

I (with my none existing JS knowledge) am trying to change the last line:

console.log(`Dark mode is ${darkModeOn ? '?? on' : '?? off'}.`);

to instead of showing it in the console.log change the browser tab icon. My idea (that I am yet to bring to life) is that:

if (dark-mode = on){ 
  $icon = "images/icon_dark.png";
}else{
  $icon = "images/icon_light.png";
  } 
}

then use the $icon in <link rel="icon" href="$icon">.
I know what I have written above is not how JS works, but it's just to illustrate what I want. I have seen other solutions, but I have found this idea to be the best for my intention.
Any help is greatly appreciated.

question from:https://stackoverflow.com/questions/65857798/js-change-browser-tab-icon-when-darkmode-is-enabled

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, you don't need PHP here, but you can do it with JavaScript.

Attach id to the element

<link rel="icon" href="images/icon_light.png" id="favicon-icon">

JS

const darkModeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
  darkModeMediaQuery.addListener((e) => {
    const darkModeOn = e.matches;
    console.log(`Dark mode is ${darkModeOn ? '?? on' : '?? off'}.`);
    document.getElementById("favicon-icon").href = darkModeOn ? 'images/icon_dark.png' : 'images/icon_light.png'
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...