动态更改网站图标

发布于 2024-11-09 10:26:16 字数 159 浏览 6 评论 0原文

我有一个根据当前登录的用户进行品牌化的 Web 应用程序。我想将页面的图标更改为自有品牌的徽标,但我找不到任何代码或任何示例来做到这一点。以前有人成功地做到过吗?

我想象一个文件夹中有十几个图标,并且对要使用的 favicon.ico 文件的引用只是与 HTML 页面一起动态生成。想法?

I have a web application that's branded according to the user that's currently logged in. I'd like to change the favicon of the page to be the logo of the private label, but I'm unable to find any code or any examples of how to do this. Has anybody successfully done this before?

I'm picturing having a dozen icons in a folder, and the reference to which favicon.ico file to use is just generated dynamically along with the HTML page. Thoughts?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

┊风居住的梦幻卍 2024-11-16 10:26:16

为什么不呢?

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';

Why not?

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';
憧憬巴黎街头的黎明 2024-11-16 10:26:16

这是一些适用于 Firefox、Opera 和 Chrome 的代码(与此处发布的其他答案不同)。这是一个不同的也可在 IE11 中运行的代码演示。以下示例可能不适用于 Safari 或 Internet Explorer。

/*!
 * Dynamically changing favicons with JavaScript
 * Works in all A-grade browsers except Safari and Internet Explorer
 * Demo: http://mathiasbynens.be/demo/dynamic-favicons
 */

// HTML5™, baby! http://mathiasbynens.be/notes/document-head
document.head = document.head || document.getElementsByTagName('head')[0];

function changeFavicon(src) {
 var link = document.createElement('link'),
     oldLink = document.getElementById('dynamic-favicon');
 link.id = 'dynamic-favicon';
 link.rel = 'shortcut icon';
 link.href = src;
 if (oldLink) {
  document.head.removeChild(oldLink);
 }
 document.head.appendChild(link);
}

然后,您可以按如下方式使用它:

var btn = document.getElementsByTagName('button')[0];
btn.onclick = function() {
 changeFavicon('http://www.google.com/favicon.ico');
};

分叉查看演示

Here’s some code that works in Firefox, Opera, and Chrome (unlike every other answer posted here). Here is a different demo of code that works in IE11 too. The following example might not work in Safari or Internet Explorer.

/*!
 * Dynamically changing favicons with JavaScript
 * Works in all A-grade browsers except Safari and Internet Explorer
 * Demo: http://mathiasbynens.be/demo/dynamic-favicons
 */

// HTML5™, baby! http://mathiasbynens.be/notes/document-head
document.head = document.head || document.getElementsByTagName('head')[0];

function changeFavicon(src) {
 var link = document.createElement('link'),
     oldLink = document.getElementById('dynamic-favicon');
 link.id = 'dynamic-favicon';
 link.rel = 'shortcut icon';
 link.href = src;
 if (oldLink) {
  document.head.removeChild(oldLink);
 }
 document.head.appendChild(link);
}

You would then use it as follows:

var btn = document.getElementsByTagName('button')[0];
btn.onclick = function() {
 changeFavicon('http://www.google.com/favicon.ico');
};

Fork away or view a demo.

难得心□动 2024-11-16 10:26:16

如果您有以下 HTML 代码段:

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

例如,您可以通过更改此链接上的 HREF 元素来使用 Javascript 更改网站图标(假设您使用的是 JQuery):

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

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

If you have the following HTML snippet:

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

You can change the favicon using Javascript by changing the HREF element on this link, for instance (assuming you're using JQuery):

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

You can also create a Canvas element and set the HREF as a ToDataURL() of the canvas, much like the Favicon Defender does.

夕色琉璃 2024-11-16 10:26:16

jQuery 版本:

$("link[rel='shortcut icon']").attr("href", "favicon.ico");

甚至更好:

$("link[rel*='icon']").attr("href", "favicon.ico");

Vanilla JS 版本:

document.querySelector("link[rel='shortcut icon']").href = "favicon.ico";

document.querySelector("link[rel*='icon']").href = "favicon.ico";

jQuery Version:

$("link[rel='shortcut icon']").attr("href", "favicon.ico");

or even better:

$("link[rel*='icon']").attr("href", "favicon.ico");

Vanilla JS version:

document.querySelector("link[rel='shortcut icon']").href = "favicon.ico";

document.querySelector("link[rel*='icon']").href = "favicon.ico";
狼性发作 2024-11-16 10:26:16

更现代的方法:

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")

A more modern approach:

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)
  }
}

You can then use it like this:

changeFavicon("http://www.stackoverflow.com/favicon.ico")
怪我鬧 2024-11-16 10:26:16

这是使图标成为表情符号或文本的片段。当我在 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('❤️');

Here's a snippet to make the favicon be an emoji, or text. It works in the console when I'm at 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('❤️');
云巢 2024-11-16 10:26:16

favicon 在 head 标签中声明如下:

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

您应该能够在视图数据中传递所需图标的名称并将其放入 head 标签中。

The favicon is declared in the head tag with something like:

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

You should be able to just pass the name of the icon you want along in the view data and throw it into the head tag.

水晶透心 2024-11-16 10:26:16

或者如果您想要表情符号:)

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/

Or if you want an emoticon :)

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());

Props to https://koddsson.com/posts/emoji-favicon/

流年里的时光 2024-11-16 10:26:16

下面是我用来向 Opera、Firefox 和 Chrome 添加动态图标支持的一些代码。但我无法让 IE 或 Safari 工作。基本上 Chrome 允许动态图标,但据我所知,它仅在页面位置(或其中的 iframe 等)发生变化时更新它们:

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]}

要更改图标,只需转到 favicon.change (“图标 URL”) 使用上述内容。

(归功于 http://softwareas.com/dynamic-favicons 我所基于的代码。)

Here's some code I use to add dynamic favicon support to Opera, Firefox and Chrome. I couldn't get IE or Safari working though. Basically Chrome allows dynamic favicons, but it only updates them when the page's location (or an iframe etc in it) changes as far as I can tell:

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]}

To change favicons, just go favicon.change("ICON URL") using the above.

(credits to http://softwareas.com/dynamic-favicons for the code I based this on.)

哭泣的笑容 2024-11-16 10:26:16

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

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

这样你就可以通过 this 获得对它的引用。

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

你可以用这个改变图片

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

in most cases, favicon is declared like this.

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

This way you can attain reference to it with this.

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

and you can change the picture with this

linkElement.href = 'url/to/any/picture/remote/or/relative';
恬淡成诗 2024-11-16 10:26:16

使此功能适用于 IE 的唯一方法是设置 Web 服务器来处理 *.ico 的请求,以调用服务器端脚本语言(PHP、.NET 等)。还设置 *.ico 以重定向到单个脚本,并让该脚本提供正确的网站图标文件。我确信如果您希望能够在同一浏览器中在不同的图标之间来回跳转,那么缓存仍然会存在一些有趣的问题。

The only way to make this work for IE is to set you web server to treat requests for *.ico to call your server side scripting language (PHP, .NET, etc). Also setup *.ico to redirect to a single script and have this script deliver the correct favicon file. I'm sure there is still going to be some interesting issues with cache if you want to be able to bounce back and forth in the same browser between different favicons.

要走干脆点 2024-11-16 10:26:16

我会使用 Greg 的方法并为 favicon.ico 制作自定义处理程序
下面是一个有效的(简化的)处理程序:

using System;
using System.IO;
using System.Web;

namespace FaviconOverrider
{
    public class IcoHandler : IHttpHandler
    {
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "image/x-icon";
        byte[] imageData = imageToByteArray(context.Server.MapPath("/ear.ico"));
        context.Response.BinaryWrite(imageData);
    }

    public bool IsReusable
    {
        get { return true; }
    }

    public byte[] imageToByteArray(string imagePath)
    {
        byte[] imageByteArray;
        using (FileStream fs = new FileStream(imagePath, FileMode.Open, FileAccess.Read))
        {
        imageByteArray = new byte[fs.Length];
        fs.Read(imageByteArray, 0, imageByteArray.Length);
        }

        return imageByteArray;
    }
    }
}

然后您可以在 IIS6 中的 Web 配置的 httpHandlers 部分中使用该处理程序,或者使用 IIS7 中的“处理程序映射”功能。

I would use Greg's approach and make a custom handler for favicon.ico
Here is a (simplified) handler that works:

using System;
using System.IO;
using System.Web;

namespace FaviconOverrider
{
    public class IcoHandler : IHttpHandler
    {
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "image/x-icon";
        byte[] imageData = imageToByteArray(context.Server.MapPath("/ear.ico"));
        context.Response.BinaryWrite(imageData);
    }

    public bool IsReusable
    {
        get { return true; }
    }

    public byte[] imageToByteArray(string imagePath)
    {
        byte[] imageByteArray;
        using (FileStream fs = new FileStream(imagePath, FileMode.Open, FileAccess.Read))
        {
        imageByteArray = new byte[fs.Length];
        fs.Read(imageByteArray, 0, imageByteArray.Length);
        }

        return imageByteArray;
    }
    }
}

Then you can use that handler in the httpHandlers section of the web config in IIS6 or use the 'Handler Mappings' feature in IIS7.

九歌凝 2024-11-16 10:26:16

对于使用 jQuery 的人来说,有一个单行解决方案:

$("link[rel*='icon']").prop("href",'https://www.stackoverflow.com/favicon.ico');

There is a single line solution for those who use jQuery:

$("link[rel*='icon']").prop("href",'https://www.stackoverflow.com/favicon.ico');
感悟人生的甜 2024-11-16 10:26:16

我在项目中使用 favico.js

它允许将图标更改为一系列预定义形状和自定义形状。

在内部,它使用 canvas 进行渲染,并使用 base64 数据 URL 进行图标编码。

该库还有一些不错的功能:图标徽章和动画;据称,您甚至可以将网络摄像头视频传输到图标中:)

I use favico.js in my projects.

It allows to change the favicon to a range of predefined shapes and also custom ones.

Internally it uses canvas for rendering and base64 data URL for icon encoding.

The library also has nice features: icon badges and animations; purportedly, you can even stream the webcam video into the icon :)

呢古 2024-11-16 10:26:16

我在开发网站时一直使用这个功能......所以我可以一目了然地看到哪个选项卡正在运行本地、开发或产品。

现在 Chrome 支持 SVG 图标,这使得它变得更加容易。

Tampermonkey 脚本

请参阅 https://gist.github.com/elliz/bb7661d8ed1535c93d03afcd0609360f一个tampermonkey 脚本,指向一个演示站点,我在 https://elliz.github.io/svg -favicon/

基本代码

改编自另一个答案...可以改进,但足以满足我的需求。

(function() {
    'use strict';

    // play with https://codepen.io/elliz/full/ygvgay for getting it right
    // viewBox is required but does not need to be 16x16
    const svg = `
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">
      <circle cx="8" cy="8" r="7.2" fill="gold" stroke="#000" stroke-width="1" />
      <circle cx="8" cy="8" r="3.1" fill="#fff" stroke="#000" stroke-width="1" />
    </svg>
    `;

    var favicon_link_html = document.createElement('link');
    favicon_link_html.rel = 'icon';
    favicon_link_html.href = svgToDataUri(svg);
    favicon_link_html.type = 'image/svg+xml';

    try {
        let favicons = document.querySelectorAll('link[rel~="icon"]');
        favicons.forEach(function(favicon) {
            favicon.parentNode.removeChild(favicon);
        });

        const head = document.getElementsByTagName('head')[0];
        head.insertBefore( favicon_link_html, head.firstChild );
    }
    catch(e) { }

    // functions -------------------------------
    function escapeRegExp(str) {
        return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
    }

    function replaceAll(str, find, replace) {
        return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
    }

    function svgToDataUri(svg) {
        // these may not all be needed - used to be for uri-encoded svg in old browsers
        var encoded = svg.replace(/\s+/g, " ")
        encoded = replaceAll(encoded, "%", "%25");
        encoded = replaceAll(encoded, "> <", "><"); // normalise spaces elements
        encoded = replaceAll(encoded, "; }", ";}"); // normalise spaces css
        encoded = replaceAll(encoded, "<", "%3c");
        encoded = replaceAll(encoded, ">", "%3e");
        encoded = replaceAll(encoded, "\"", "'"); // normalise quotes ... possible issues with quotes in <text>
        encoded = replaceAll(encoded, "#", "%23"); // needed for ie and firefox
        encoded = replaceAll(encoded, "{", "%7b");
        encoded = replaceAll(encoded, "}", "%7d");
        encoded = replaceAll(encoded, "|", "%7c");
        encoded = replaceAll(encoded, "^", "%5e");
        encoded = replaceAll(encoded, "`", "%60");
        encoded = replaceAll(encoded, "@", "%40");
        var dataUri = 'data:image/svg+xml;charset=UTF-8,' + encoded.trim();
        return dataUri;
    }

})();

只需将您自己的 SVG(如果您使用工具的话,可以使用 Jake Archibald 的 SVGOMG 进行清理)放入顶部的 const 中即可。确保它是方形的(使用 viewBox 属性),然后就可以开始了。

I use this feature all the time when developing sites ... so I can see at-a-glance which tab has local, dev or prod running in it.

Now that Chrome supports SVG favicons it makes it a whole lot easier.

Tampermonkey Script

Have a gander at https://gist.github.com/elliz/bb7661d8ed1535c93d03afcd0609360f for a tampermonkey script that points to a demo site I chucked up at https://elliz.github.io/svg-favicon/

Basic code

Adapted this from another answer ... could be improved but good enough for my needs.

(function() {
    'use strict';

    // play with https://codepen.io/elliz/full/ygvgay for getting it right
    // viewBox is required but does not need to be 16x16
    const svg = `
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">
      <circle cx="8" cy="8" r="7.2" fill="gold" stroke="#000" stroke-width="1" />
      <circle cx="8" cy="8" r="3.1" fill="#fff" stroke="#000" stroke-width="1" />
    </svg>
    `;

    var favicon_link_html = document.createElement('link');
    favicon_link_html.rel = 'icon';
    favicon_link_html.href = svgToDataUri(svg);
    favicon_link_html.type = 'image/svg+xml';

    try {
        let favicons = document.querySelectorAll('link[rel~="icon"]');
        favicons.forEach(function(favicon) {
            favicon.parentNode.removeChild(favicon);
        });

        const head = document.getElementsByTagName('head')[0];
        head.insertBefore( favicon_link_html, head.firstChild );
    }
    catch(e) { }

    // functions -------------------------------
    function escapeRegExp(str) {
        return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
    }

    function replaceAll(str, find, replace) {
        return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
    }

    function svgToDataUri(svg) {
        // these may not all be needed - used to be for uri-encoded svg in old browsers
        var encoded = svg.replace(/\s+/g, " ")
        encoded = replaceAll(encoded, "%", "%25");
        encoded = replaceAll(encoded, "> <", "><"); // normalise spaces elements
        encoded = replaceAll(encoded, "; }", ";}"); // normalise spaces css
        encoded = replaceAll(encoded, "<", "%3c");
        encoded = replaceAll(encoded, ">", "%3e");
        encoded = replaceAll(encoded, "\"", "'"); // normalise quotes ... possible issues with quotes in <text>
        encoded = replaceAll(encoded, "#", "%23"); // needed for ie and firefox
        encoded = replaceAll(encoded, "{", "%7b");
        encoded = replaceAll(encoded, "}", "%7d");
        encoded = replaceAll(encoded, "|", "%7c");
        encoded = replaceAll(encoded, "^", "%5e");
        encoded = replaceAll(encoded, "`", "%60");
        encoded = replaceAll(encoded, "@", "%40");
        var dataUri = 'data:image/svg+xml;charset=UTF-8,' + encoded.trim();
        return dataUri;
    }

})();

Just pop your own SVG (maybe cleaned with Jake Archibald's SVGOMG if you're using a tool) into the const at the top. Make sure it is square (using the viewBox attribute) and you're good to go.

冷情 2024-11-16 10:26:16

根据WikiPedia,您可以使用链接指定要加载的favicon文件head 部分中的 code> 标记,参数为 rel="icon"

例如:

 <link rel="icon" type="image/png" href="/path/image.png">

我想如果您想为该调用编写一些动态内容,您将可以访问 cookie,以便您可以以这种方式检索会话信息并呈现适当的内容。

您可能会遇到文件格式的问题(据报道,IE 只支持 .ICO 格式,而大多数其他人都支持 PNG 和 GIF 图像),并且可能会在浏览器上和通过代理遇到缓存问题。这是因为 favicon 的最初目的,特别是用网站的迷你徽标标记书签。

According to WikiPedia, you can specify which favicon file to load using the link tag in the head section, with a parameter of rel="icon".

For example:

 <link rel="icon" type="image/png" href="/path/image.png">

I imagine if you wanted to write some dynamic content for that call, you would have access to cookies so you could retrieve your session information that way and present appropriate content.

You may fall foul of file formats (IE reportedly only supports it's .ICO format, whilst most everyone else supports PNG and GIF images) and possibly caching issues, both on the browser and through proxies. This would be because of the original itention of favicon, specifically, for marking a bookmark with a site's mini-logo.

回忆那么伤 2024-11-16 10:26:16

是的,完全可能

  • 在 favicon.ico(和其他文件链接)之后使用查询字符串 -
    请参阅下面的答案链接)
  • 只需确保服务器响应“someUserId”
    正确的图像文件(可能是静态路由规则,或者
    动态服务器端代码)。

例如

<link rel="shortcut icon" href="/favicon.ico?userId=someUserId">

,然后无论您使用什么服务器端语言/框架都应该能够轻松地根据用户ID找到文件并在响应该请求时提供它嗯>。

但是要正确地制作网站图标(这实际上是一个非常复杂的主题),请在此处查看答案https://stackoverflow.com/a/45301651/661584

比解决所有细节容易得多你自己。

享受。

Yes totally possible

  • Use a querystring after the favicon.ico (and other files links -
    see answer link below)
  • Simply make sure the server responds to the "someUserId" with
    the correct image file (that could be static routing rules, or
    dynamic server side code).

e.g.

<link rel="shortcut icon" href="/favicon.ico?userId=someUserId">

Then whatever server side language / framework you use should easily be able to find the file based on the userId and serve it up in response to that request.

But to do favicons properly (its actually a really complex subject) please see the answer here https://stackoverflow.com/a/45301651/661584

A lot lot easier than working out all the details yourself.

Enjoy.

凶凌 2024-11-16 10:26:16

在 Chrome 上测试 2021 年提出的解决方案时,我发现有时浏览器会缓存 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
如果其他人也有同样的问题

Testing the proposed solutions on 2021 on Chrome, I found that some times the browser cache the favicon and do not show the change, even if the link was changed

This code worked (similar to previous proposal but adds a random parameter to avoid caching)

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);

Copied from https://gist.github.com/mathiasbynens/428626#gistcomment-1809869
in case that someone else have the same problem

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文