我有一个网络应用程序,根据当前登录的用户进行标记。我想将页面的图标更改为私有标签的标志,但我无法找到如何做到这一点的任何代码或任何示例。以前有人成功做到过吗?
我想象在一个文件夹中有12个图标,使用哪个favicon.ico文件的引用是与HTML页面一起动态生成的。想法吗?
我有一个网络应用程序,根据当前登录的用户进行标记。我想将页面的图标更改为私有标签的标志,但我无法找到如何做到这一点的任何代码或任何示例。以前有人成功做到过吗?
我想象在一个文件夹中有12个图标,使用哪个favicon.ico文件的引用是与HTML页面一起动态生成的。想法吗?
当前回答
对于那些使用jQuery的人来说,有一个单行解决方案:
$("link[rel*='icon']").prop("href",'https://www.stackoverflow.com/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'特性。
或者如果你想要一个表情符号:)
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标记中。
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";