如何在javascript变量中存储任何url的favicon.ico?

时间:2017-10-28 12:55:02

标签: javascript

好的,我知道如何获取和显示任何网址的图标....通过这个:

icon[x].setAttribute("src","http://"+ curl + "/favicon.ico")
  

"卷曲"是特定网址的域名

但是在为任何网址设置图标之前,我想检查它是否实际上已经获取了任何图标。因为某些网站没有提取favicon,并且我的网页上没有显示该网址的图标。所以基本上我想首先在变量中获取favicon并检查变量中是否有任何图标。如果没有,它会放一个默认图像。 我只想知道如何获取一个图标以存储在变量中,然后检查是否存在任何图像。

This is my code...Please check it once

1 个答案:

答案 0 :(得分:0)

修改

如果我理解你的问题,我不是百分百肯定的。

var icon = '';
for(var a = 0; a < document.getElementsByTagName('link').length;a++) { 
 if(document.getElementsByTagName('link')[a].getAttribute('rel') == 'shortcut icon') {
  // favicon found
  icon = document.getElementsByTagName('link')[a].getAttribute('href');
 }
}
// if no favicon is found, 'icon' is an empty string
// and a new DOM element ("link") needs to be added to show the icon
if(icon == '') {
 var node = document.createElement("LINK"); 
 node.setAttribure('rel', 'shortcut icon');
 node.setAttribute('href','http://link.to/favicon.ico');
 document.getElementsByTagName('head')[0].appendChild(node);
}