Javascript 动态更改网站favicon
我有一个web应用程序,它的品牌是根据当前登录的用户而定的。我想将页面的favicon更改为私有标签的徽标,但我找不到任何代码或示例来说明如何执行此操作。以前有人成功地做到过吗Javascript 动态更改网站favicon,javascript,html,dom,favicon,Javascript,Html,Dom,Favicon,我有一个web应用程序,它的品牌是根据当前登录的用户而定的。我想将页面的favicon更改为私有标签的徽标,但我找不到任何代码或示例来说明如何执行此操作。以前有人成功地做到过吗 我正在想象一个文件夹中有十几个图标,favicon.ico文件要使用的引用只是随着HTML页面动态生成的。想法?favicon在head标签中声明为: <link rel="shortcut icon" type="image/ico" href="favicon.ico"> 您应该能够在视图数据中传递
我正在想象一个文件夹中有十几个图标,favicon.ico文件要使用的引用只是随着HTML页面动态生成的。想法?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.getElementsByTagName('head')[0].appendChild(link);
}
link.href = 'https://stackoverflow.com/favicon.ico';
如果您有以下HTML代码段:
<link id="favicon" rel="shortcut icon" type="image/png" href="favicon.png" />
您还可以创建一个Canvas元素,并将HREF设置为Canvas的ToDataURL(),就像设置一样。根据,您可以使用标题
部分中的链接
标记指定要加载的favicon文件,参数为rel=“icon”
例如:
<link rel="icon" type="image/png" href="/path/image.png">
我想,如果您想为该调用编写一些动态内容,您可以访问cookies,这样您就可以通过这种方式检索会话信息并呈现适当的内容
在浏览器和代理上,您可能会遇到文件格式问题(即据说只支持.ICO格式,而大多数其他人都支持PNG和GIF图像)以及可能的缓存问题。这可能是因为favicon最初的iEntation,特别是用站点的迷你徽标标记书签。以下是我用来向Opera、Firefox和Chrome添加动态favicon支持的一些代码。但我无法让IE或Safari工作。基本上,Chrome允许动态favicon,但据我所知,它只在页面位置(或
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]}
var IE=navigator.userAgent.indexOf(“MSIE”)=-1.
var favicon={
更改:功能(iconURL){
if(arguments.length==2){
document.title=optionalDocTitle}
this.addLink(iconURL,“图标”)
this.addLink(iconURL,“快捷方式图标”)
//Google Chrome HACK-每当IFrame更改位置时
//(甚至到:空白),出于某种原因,它会更新favicon
//不过,它在Safari上根本不起作用:-(
如果(!IE){//禁用IE“click”声音
如果(!window.\u IFrame){
__IFrame=document.createElement('IFrame')
var s=\uu IFrame.style
s、 高度=s.width=s.left=s.top=s.border=0
s、 位置='绝对'
s、 可见性=‘隐藏’
document.body.appendChild(\uu IFrame)}
__IFrame.src='about:blank'}},
addLink:函数(iconURL、relValue){
var link=document.createElement(“链接”)
link.type=“图像/x图标”
link.rel=relValue
link.href=iconURL
此.removeLinkIfExists(relValue)
this.docHead.appendChild(link)},
removeLinkIfExists:函数(relValue){
var links=this.docHead.getElementsByTagName(“链接”);
对于(var i=0;i这里有一些代码可以在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');
};
或者。为IE实现此功能的唯一方法是将web服务器设置为处理*.ico请求,以调用服务器端脚本语言(PHP、.NET等)。同时设置*.ico以重定向到单个脚本,并使此脚本提供正确的favicon文件。如果您希望能够在同一浏览器中的不同favicon之间来回跳转,我相信缓存仍会有一些有趣的问题。我将使用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中使用“处理程序映射”功能。jQuery版本:
$("link[rel='shortcut icon']").attr("href", "favicon.ico");
document.querySelector("link[rel='shortcut icon']").href = "favicon.ico";
document.querySelector("link[rel*='icon']").href = "favicon.ico";
或者更好:
$("link[rel*='icon']").attr("href", "favicon.ico");
香草JS版本:
$("link[rel='shortcut icon']").attr("href", "favicon.ico");
document.querySelector("link[rel='shortcut icon']").href = "favicon.ico";
document.querySelector("link[rel*='icon']").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)
}
}
是完全可能的
- 在favicon.ico(和其他文件链接)之后使用查询字符串-
请参阅下面的答案链接)
- 只需确保服务器使用
正确的图像文件(可能是静态的路由规则,或
动态服务器端代码)
e、 g
然后,无论您使用哪种服务器端语言/框架,都应该能够轻松地根据用户ID找到文件,并根据该请求提供该文件
但是要正确地做favicon(实际上这是一个非常复杂的主题)请看这里的答案
比自己解决所有细节容易得多
享受。我在项目中使用
它允许将favicon更改为一系列预定义的形状以及自定义形状
在内部,它使用canvas
进行渲染,并使用base64
数据URL进行图标编码
该库还具有很好的功能:图标徽章和动画;据称,您甚至可以将网络摄像头视频流到图标中:)对于使用jQuery的用户,有一个单行解决方案:
$("link[rel*='icon']").prop("href",'https://www.stackoverflow.com/favicon.ico');
或者,如果您想要一个表情符号:)
我在开发站点时一直使用此功能……因此我可以一目了然地看到哪个选项卡中运行着本地、开发或产品
现在Chrome支持SVG favicons,这让它变得简单多了
密文
有一个篡改猴子脚本,指向一个演示网站,我扔了一个甘德在
基本代码
改编自另一个答案…可以改进,但足够好
$("link[rel*='icon']").prop("href",'https://www.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());
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('❤️');