代码之家  ›  专栏  ›  技术社区  ›  patrick

有没有办法将页面的图标改为“正在加载/忙碌”?[副本]

  •  0
  • patrick  · 技术社区  · 7 年前

    我想象着在一个文件夹里有十几个图标,以及其中的引用favicon.ico公司要使用的文件只是随HTML页面动态生成的。思想?

    0 回复  |  直到 9 年前
        1
  •  436
  •   Chris Morgan    5 年前

    为什么不呢?

    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';
    
        2
  •  94
  •   robocat    7 年前

    demo of code that works in 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');
    };
    

    Fork away view a demo .

        3
  •  50
  •   orip    15 年前

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

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

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

    Favicon Defender 做。

        4
  •  39
  •   ndugger vorillaz    10 年前

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

    或者更好:

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

    香草JS版本:

    document.querySelector("link[rel='shortcut icon']").href = "favicon.ico";
    
    document.querySelector("link[rel*='icon']").href = "favicon.ico";
    
        5
  •  19
  •   Michał Perłakowski    9 年前

    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")
    
        6
  •  11
  •   rubo77    11 年前

    favicon在head标签中声明如下:

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

        7
  •  9
  •   cryo    15 年前

    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("ICON URL") 使用上述方法。

    http://softwareas.com/dynamic-favicons 对于我基于此的代码。)

        8
  •  4
  •   Dan    14 年前

    下面是一个(简化的)处理程序:

    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中使用“处理程序映射”特性。

        9
  •  4
  •   Pepelegal    7 年前

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

    $("link[rel*='icon']").prop("href",'https://www.stackoverflow.com/favicon.ico');
    
        10
  •  4
  •   max4ever    7 年前

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

    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/

        11
  •  3
  •   Greg    15 年前

    对于IE来说,实现这一点的唯一方法是将web服务器设置为处理*.ico的请求,以调用服务器端脚本语言(PHP、.NET等)。另外,设置*.ico重定向到单个脚本,并让该脚本传递正确的favicon文件。我敢肯定,如果你想在同一个浏览器中在不同的favicon之间来回跳转,cache仍然会有一些有趣的问题。

        12
  •  2
  •   staticsan    17 年前

    根据 WikiPedia ,可以使用 link 标签在 head 节,参数为 rel="icon" .

    例如:

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

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

        13
  •  2
  •   MemeDeveloper    8 年前

    • 使用 查询字符串 参见下面的答案链接)
    • 只需确保服务器对“someUserId”作出响应 静止的 路由规则,或

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

    任何服务器端语言/框架 你应该很容易就能找到 把它端上来

    但要做正确的事 真正地 复杂主题)请看这里的答案 https://stackoverflow.com/a/45301651/661584

    好好享受。

        14
  •  1
  •   Dima Tisnek    7 年前

    favico.js 在我的项目中。

    canvas base64 图标编码的数据URL。

    这个库还有很好的特性:图标徽章和动画;据说,你甚至可以将网络摄像头视频流到图标:)

        15
  •  1
  •   Ruskin    5 年前

    现在Chrome支持SVG favicons,这让它变得简单多了。

    唐僧书

    痛饮 https://gist.github.com/elliz/bb7661d8ed1535c93d03afcd0609360f 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属性)并且可以继续。