我有一个网络应用程序,根据当前登录的用户进行标记。我想将页面的图标更改为私有标签的标志,但我无法找到如何做到这一点的任何代码或任何示例。以前有人成功做到过吗?
我想象在一个文件夹中有12个图标,使用哪个favicon.ico文件的引用是与HTML页面一起动态生成的。想法吗?
我有一个网络应用程序,根据当前登录的用户进行标记。我想将页面的图标更改为私有标签的标志,但我无法找到如何做到这一点的任何代码或任何示例。以前有人成功做到过吗?
我想象在一个文件夹中有12个图标,使用哪个favicon.ico文件的引用是与HTML页面一起动态生成的。想法吗?
当前回答
或者如果你想要一个表情符号:)
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/
其他回答
2021年在Chrome上测试提出的解决方案时,我发现浏览器有时会缓存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 以防别人有同样的问题
唯一的方法,使此工作的IE是设置您的web服务器处理*.ico请求调用您的服务器端脚本语言(PHP, . net等)。还设置*.ico重定向到单个脚本,并让该脚本交付正确的favicon文件。我敢肯定,如果你想在同一个浏览器中在不同的favicon之间来回跳转,缓存仍然会有一些有趣的问题。
是的,完全可能
在favicon.ico(和其他文件链接- 见下面的答案链接) 只需确保服务器响应“someUserId” 正确的映像文件(可以是静态路由规则或 动态服务器端代码)。
如。
<link rel="shortcut icon" href="/favicon.ico?userId=someUserId">
然后,无论您使用何种服务器端语言/框架,都应该能够轻松地基于userId找到该文件,并响应该请求。
但是要正确地做favicons(这实际上是一个非常复杂的主题),请在这里看到答案https://stackoverflow.com/a/45301651/661584
这比你自己解决所有细节要容易得多。
享受。
一个更现代的方法:
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")
下面是一些可以在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');
};
叉子或查看演示。