問題描述

我有一個根據使用者登入的網路應用程式,我想將頁面的圖示改為私人標籤的標誌,但是我找不到任何程式碼或任何示例去做這個。有人成功完成了嗎?

我在一個資料夾中繪製了十幾個圖示,並且使用 favicon.ico 檔案的引用只是與 HTML 頁面一起生成的。思考?

最佳解決方案

為什麼不?

(function() {
    var link = document.querySelector("link[rel*='icon']") || document.createElement('link');
    link.type = 'image/x-icon';
    link.rel = 'shortcut icon';
    link.href = 'http://www.stackoverflow.com/favicon.ico';
    document.getElementsByTagName('head')[0].appendChild(link);
})();

Firefox 應該很酷。

編輯以正確覆蓋現有圖示

次佳解決方案

以下是 Firefox,Opera 和 Chrome 中的一些程式碼 (與此處釋出的其他答案不同) 。仍然在 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 awayview a demo

第三種解決方案

如果您有以下 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 一樣。

第四種方案

jQuery 版本:

$("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";

第五種方案

以下是我為 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]}

要改變 favicons,只需使用上面的 favicon.change("ICON URL")

(以 http://softwareas.com/dynamic-favicons 為基礎的程式碼 I) 。

第六種方案

標籤在 head 標籤中被宣告為:

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

您應該能夠在檢視資料中傳遞所需圖示的名稱,並將其放入頭標。

第七種方案

更現代的方法:

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

第八種方案

我會使用 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 中使用’Handler Mappings’ 功能。

第九種方案

使 IE 工作的唯一方法是設定您的 Web 伺服器來處理* .ico 的請求來呼叫您的伺服器端指令碼語言 (PHP,.NET 等) 。還要設定* .ico 重定向到單個指令碼,並使此指令碼提供正確的圖示檔案。如果您希望能夠在不同的 favicons 之間的同一瀏覽器中來回彈起來,我確定快取中還有一些有趣的問題。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇