我有一个网络应用程序,根据当前登录的用户进行标记。我想将页面的图标更改为私有标签的标志,但我无法找到如何做到这一点的任何代码或任何示例。以前有人成功做到过吗?
我想象在一个文件夹中有12个图标,使用哪个favicon.ico文件的引用是与HTML页面一起动态生成的。想法吗?
我有一个网络应用程序,根据当前登录的用户进行标记。我想将页面的图标更改为私有标签的标志,但我无法找到如何做到这一点的任何代码或任何示例。以前有人成功做到过吗?
我想象在一个文件夹中有12个图标,使用哪个favicon.ico文件的引用是与HTML页面一起动态生成的。想法吗?
当前回答
对于那些使用jQuery的人来说,有一个单行解决方案:
$("link[rel*='icon']").prop("href",'https://www.stackoverflow.com/favicon.ico');
其他回答
是的,完全可能
在favicon.ico(和其他文件链接- 见下面的答案链接) 只需确保服务器响应“someUserId” 正确的映像文件(可以是静态路由规则或 动态服务器端代码)。
如。
<link rel="shortcut icon" href="/favicon.ico?userId=someUserId">
然后,无论您使用何种服务器端语言/框架,都应该能够轻松地基于userId找到该文件,并响应该请求。
但是要正确地做favicons(这实际上是一个非常复杂的主题),请在这里看到答案https://stackoverflow.com/a/45301651/661584
这比你自己解决所有细节要容易得多。
享受。
为什么不呢?
var link = document.querySelector("link[rel~='icon']");
if (!link) {
link = document.createElement('link');
link.rel = 'icon';
document.head.appendChild(link);
}
link.href = 'https://stackoverflow.com/favicon.ico';
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 以防别人有同样的问题
下面是我用来为Opera、Firefox和Chrome添加动态图标支持的一些代码。不过我无法让IE或Safari正常工作。基本上Chrome允许动态favicons,但只有当页面的位置(或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,只需访问favicon。更改("ICON URL")使用上述。
(我基于http://softwareas.com/dynamic-favicons的代码。)
favicon在head标签中声明,如下所示:
<link rel="shortcut icon" type="image/ico" href="favicon.ico">
您应该能够在视图数据中传递您想要的图标的名称,并将其扔到head标记中。