Change favicon, using Visibility API

Viewed 53

I have seen some websites (discord. hotjar), using the Visibility API to show a bullet when the tab is inactive, and hide it when its active again,

How we can do that?

enter image description here

1 Answers

For this, you need to create two different favicons for each mode and toggle between them using the Visibility API. Something like this:

// Set the name of the hidden property and the change event for visibility
let hidden;
let visibilityChange;
if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support
  hidden = "hidden";
  visibilityChange = "visibilitychange";
} else if (typeof document.msHidden !== "undefined") {
  hidden = "msHidden";
  visibilityChange = "msvisibilitychange";
} else if (typeof document.webkitHidden !== "undefined") {
  hidden = "webkitHidden";
  visibilityChange = "webkitvisibilitychange";
}

var link = document.querySelector("link[rel~='icon']");
if (!link) {
    link = document.createElement('link');
    link.rel = 'icon';
    document.getElementsByTagName('head')[0].appendChild(link);
}

function handleVisibilityChange() {
  if (document[hidden]) {
    link.href = 'https://www.linkpicture.com/q/favicon2.ico';
  } else {
    link.href = 'https://www.linkpicture.com/q/favicon1_1.ico';
  }
}

// Warn if the browser doesn't support addEventListener or the Page Visibility API
if (typeof document.addEventListener === "undefined" || hidden === undefined) {
  console.log("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
} else {
  // Handle page visibility change
  document.addEventListener(visibilityChange, handleVisibilityChange, false);
}

Preview: enter image description here

Related