每个网页都有自己的图标,开发浏览器时需要给标签设置图标,如何获取网页的图标呢?
图标在html中的格式举例:
//百度(完整的图标网址)
<link rel="shortcut icon" href="https://www.baidu.com/favicon.ico" type="image/x-icon" />
//360(不含协议的网址)
<link rel="shortcut icon" href="//ss.360tres.com/static/121a1737750aa53d.ico" type="image/x-icon">
//其他(相对路径的网址)
<link rel="icon" href="/static/fav.ico" type="image/x-icon" />
从中找到共同点,去识别link标签且rel中有icon的即可,JavaScript代码:
var links = document.getElementsByTagName('link');
var iconUrl= '';
for (var i = 0; i < links.length; ++i) {
var rel = links[i].getAttribute('rel');
if (rel && rel.indexOf('icon') >= 0) {
iconUrl = links[i].getAttribute('href');
break;
}
}
if (iconUrl.indexOf('//') == 0) {
//不含协议的图标网址
var protocal = window.location.protocol;
iconUrl = protocal + iconUrl;
}else if (iconUrl.indexOf('http') < 0) {
//相对路径的图标网址
var domain = window.location.origin;
iconUrl = domain + iconUrl;
}
iconUrl;