我有一个网络应用程序,根据当前登录的用户进行标记。我想将页面的图标更改为私有标签的标志,但我无法找到如何做到这一点的任何代码或任何示例。以前有人成功做到过吗?

我想象在一个文件夹中有12个图标,使用哪个favicon.ico文件的引用是与HTML页面一起动态生成的。想法吗?


当前回答

为什么不呢?

var link = document.querySelector("link[rel~='icon']");
if (!link) {
    link = document.createElement('link');
    link.rel = 'icon';
    document.head.appendChild(link);
}
link.href = 'https://stackoverflow.com/favicon.ico';

其他回答

或者如果你想要一个表情符号:)

var canvas = document.createElement("canvas");
canvas.height = 64;
canvas.width = 64;

var ctx = canvas.getContext("2d");
ctx.font = "64px serif";
ctx.fillText("☠️", 0, 64); 

$("link[rel*='icon']").prop("href", canvas.toDataURL());

道具https://koddsson.com/posts/emoji-favicon/

favicon在head标签中声明,如下所示:

<link rel="shortcut icon" type="image/ico" href="favicon.ico">

您应该能够在视图数据中传递您想要的图标的名称,并将其扔到head标记中。

为什么不呢?

var link = document.querySelector("link[rel~='icon']");
if (!link) {
    link = document.createElement('link');
    link.rel = 'icon';
    document.head.appendChild(link);
}
link.href = 'https://stackoverflow.com/favicon.ico';

如果你有以下HTML片段:

<link id="favicon" rel="shortcut icon" type="image/png" href="favicon.png" />

你可以使用Javascript通过改变这个链接上的HREF元素来改变favicon,例如(假设你正在使用JQuery):

$("#favicon").attr("href","favicon2.png");

您还可以创建一个Canvas元素,并将HREF设置为画布的ToDataURL(),就像Favicon Defender所做的那样。

在大多数情况下,favicon是这样声明的。

<link rel="icon" href"...." />

这样你就可以得到它的参考。

const linkElement = document.querySelector('link[rel=icon]');

你可以用这个改变图像

linkElement.href = 'url/to/any/picture/remote/or/relative';