我有一个网络应用程序,根据当前登录的用户进行标记。我想将页面的图标更改为私有标签的标志,但我无法找到如何做到这一点的任何代码或任何示例。以前有人成功做到过吗?
我想象在一个文件夹中有12个图标,使用哪个favicon.ico文件的引用是与HTML页面一起动态生成的。想法吗?
我有一个网络应用程序,根据当前登录的用户进行标记。我想将页面的图标更改为私有标签的标志,但我无法找到如何做到这一点的任何代码或任何示例。以前有人成功做到过吗?
我想象在一个文件夹中有12个图标,使用哪个favicon.ico文件的引用是与HTML页面一起动态生成的。想法吗?
当前回答
在大多数情况下,favicon是这样声明的。
<link rel="icon" href"...." />
这样你就可以得到它的参考。
const linkElement = document.querySelector('link[rel=icon]');
你可以用这个改变图像
linkElement.href = 'url/to/any/picture/remote/or/relative';
其他回答
一个更现代的方法:
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)
}
}
然后你可以这样使用它:
changeFavicon("http://www.stackoverflow.com/favicon.ico")
根据WikiPedia,你可以使用头部部分的链接标签指定加载哪个favicon文件,参数rel="icon"。
例如:
<link rel="icon" type="image/png" href="/path/image.png">
我想,如果您想为该调用编写一些动态内容,那么您就可以访问cookie,以便以这种方式检索会话信息并显示适当的内容。
你可能会遇到文件格式的问题(据报道IE只支持。ico格式,而大多数人都支持PNG和GIF图像),也可能会遇到缓存问题,无论是在浏览器上还是通过代理。这可能是因为favicon最初的意图,特别是用网站的迷你标志标记书签。
对于那些使用jQuery的人来说,有一个单行解决方案:
$("link[rel*='icon']").prop("href",'https://www.stackoverflow.com/favicon.ico');
下面是一个片段,使favicon成为一个表情符号或文本。当我在stackoverflow时,它在控制台工作。
function changeFavicon(text) {
const canvas = document.createElement('canvas');
canvas.height = 64;
canvas.width = 64;
const ctx = canvas.getContext('2d');
ctx.font = '64px serif';
ctx.fillText(text, 0, 64);
const link = document.createElement('link');
const oldLinks = document.querySelectorAll('link[rel="shortcut icon"]');
oldLinks.forEach(e => e.parentNode.removeChild(e));
link.id = 'dynamic-favicon';
link.rel = 'shortcut icon';
link.href = canvas.toDataURL();
document.head.appendChild(link);
}
changeFavicon('❤️');
2021年在Chrome上测试提出的解决方案时,我发现浏览器有时会缓存favicon,即使链接发生了变化,也不会显示更改
这段代码可以工作(类似于前面的建议,但添加了一个随机参数以避免缓存)
let oldFavicon = document.getElementById('favicon')
var link = document.createElement('link')
link.id = 'favicon';
link.type = 'image/x-icon'
link.rel = 'icon';
link.href = new_favicon_url +'?=' + Math.random();
if (oldFavicon) {
document.head.removeChild(oldFavicon);
}
document.head.appendChild(link);
摘自https://gist.github.com/mathiasbynens/428626#gistcomment-1809869 以防别人有同样的问题