var link = document.querySelector("link[rel~='icon']");
if (!link) {
link = document.createElement('link');
link.rel = 'icon';
document.getElementsByTagName('head')[0].appendChild(link);
}
link.href = 'https://stackoverflow.com/favicon.ico';
var IE = navigator.userAgent.indexOf("MSIE")!=-1
var favicon = {
change: function(iconURL) {
if (arguments.length == 2) {
document.title = optionalDocTitle}
this.addLink(iconURL, "icon")
this.addLink(iconURL, "shortcut icon")
// Google Chrome HACK - whenever an IFrame changes location
// (even to about:blank), it updates the favicon for some reason
// It doesn't work on Safari at all though :-(
if (!IE) { // Disable the IE "click" sound
if (!window.__IFrame) {
__IFrame = document.createElement('iframe')
var s = __IFrame.style
s.height = s.width = s.left = s.top = s.border = 0
s.position = 'absolute'
s.visibility = 'hidden'
document.body.appendChild(__IFrame)}
__IFrame.src = 'about:blank'}},
addLink: function(iconURL, relValue) {
var link = document.createElement("link")
link.type = "image/x-icon"
link.rel = relValue
link.href = iconURL
this.removeLinkIfExists(relValue)
this.docHead.appendChild(link)},
removeLinkIfExists: function(relValue) {
var links = this.docHead.getElementsByTagName("link");
for (var i=0; i<links.length; i++) {
var link = links[i]
if (link.type == "image/x-icon" && link.rel == relValue) {
this.docHead.removeChild(link)
return}}}, // Assuming only one match at most.
docHead: document.getElementsByTagName("head")[0]}
const changeFavicon = link => {
let $favicon = document.querySelector('link[rel="icon"]')
// If a <link rel="icon"> element already exists,
// change its href to the given link.
if ($favicon !== null) {
$favicon.href = link
// Otherwise, create a new element and append it to <head>.
} else {
$favicon = document.createElement("link")
$favicon.rel = "icon"
$favicon.href = link
document.head.appendChild($favicon)
}
}