我在网站上运行用户脚本(使用 tampermonkey),我有一个函数,每次页面上的其他内容发生变化时都会调用该函数。
我有一个值存储在名为 Available
的东西中。如果这是 0,那么我想使用该站点的标准图标。否则,我希望将一个红色框添加到 favicon,其中包含显示 Available
值的文本。
这最初有效,但是在 Available
变为 > 0,然后 == 0,然后再次 > 0 之后,它停止添加顶部带有白色文本的红色框。
代码肯定每次都到达关键点,因为我的控制台日志显示正在触发 Available
的值。
这是我所拥有的:
if(Available > 0){
var canvas = document.createElement('canvas');
canvas.width = 16;canvas.height = 16;
var ctx = canvas.getContext('2d');
var img = new Image();
img.src = '/favicon.ico';
img.onload = function() {
ctx.drawImage(img, 0, 0);
ctx.fillStyle = "#F00";
ctx.fillRect(10, 7, 6, 8);
ctx.fillStyle = '#FFFFFF';
ctx.font = 'bold 10px sans-serif';
ctx.fillText(Available, 10, 14);
var link = document.createElement('link');
link.type = 'image/x-icon';
link.rel = 'shortcut icon';
link.href = canvas.toDataURL("image/x-icon");
document.getElementsByTagName('head')[0].appendChild(link);
};
}
else {
var canvas2 = document.createElement('canvas');
canvas2.width = 16;
canvas2.height = 16;
var ctx2 = canvas2.getContext('2d');
var img2 = new Image();
img2.src = '/favicon.ico';
img2.onload = function() {
ctx2.drawImage(img2, 0, 0);
var link2 = document.createElement('link');
link2.type = 'image/x-icon';
link2.rel = 'shortcut icon';
link2.href = canvas2.toDataURL("image/x-icon");
document.getElementsByTagName('head')[0].appendChild(link2);
};
}
最佳答案
您很可能需要删除之前添加的图标链接,这样浏览器就不会继续使用您添加的第一个:
var oldLinks = document.querySelectorAll('link[rel*="icon"]');
for (var i = oldLinks.length - 1; i >= 0; --i) {
var ln = oldLinks[i],
pn = ln.parentNode;
pn.removeChild(ln);
}
if (Available > 0) {
// as before
}
关于javascript - 动态多次来回更改图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44826941/