JavaScript(js)获取网页的图标地址

Source

每个网页都有自己的图标,开发浏览器时需要给标签设置图标,如何获取网页的图标呢?

图标在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">

//抖店服务市场(base64图片)

<link rel="icon" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAaCAYAAACkVDyJAAAABmJLR0QA/wD/AP+gvaeTAAAC00lEQVRIibWWzUtUURTAf+c6aqlhEEGZJNKIhR9Fi4qWQUWQmpa7/oC20TbCQApqE22KFhLRIhJyCNpYUK2CVqbSN5lGRpEaEmo2806Lmd6c+5w3atBd3Xu+fufce+59T/jfo0trySAABMzLf4V16gbgu5FcT8Qad+h+HO0IjQRURbSjpOT0skChFfUkb5cC27UGRx/CYQAUiO6DML4sLOvbEvGLALu0DuUpULdMqNEVAaE5CnThokcdyp0VwCBgZIVAW+EvWhjLVzhEJ8I+Y6AIfQRc4zcfvDAVzIbzDr2BI5nzmCfFURAFFfwKX9Ej6TxQOOEFVXoZkHNF8+9RxxBNKOU5yXgWBhyn3ms2ze6KM+57zHyWUi4WhQEMsRVCGAjvDSB6fiMA2Qq7tYo09cb4Gf0yn9NVs0ircfxESj7m7JJeBwce0O9QLDBDM7b5xTRFhh0IJ02g20AW6Eh690wiQJtMhuGsS5Fscllv8TQJPpugSU9nm0u8mNPcl8l4oDNAMUBBWceksbTAKR7IDABHtBxoKFSAK5BNBsdrU4WtcIqbsgBAt64Faowuv51r2A6UmkQjQGgyju/ChjmklcD6UBOY7UyzDdvlWrRhwpfJ0aWbgY1Gmd/Oysj5uSLnZyt0EWDGVhjEZ4N6WwZizi8KdLEVKsLLvJkUvqC5uV9h2lToPGBANWNmbWNOkJIffxcJhBbvLqW9h/kFykS4KueryfsewmAOt2CaqZo0tSaG99AnCGj2LugCX8L5gMR/hlIyWFCe4QBxjwjZLW3wHCq8jl3daNMKlLOeLOC5XSaAMs9AuMUxPUUpw8xFfhDihqOEMnYRcAHYbTQzlPLIBwrDKHuNrBHhMeklqRQfQUFpL/3y088Nrq4i7GrGXXZyJSrMHm6nXgbOsPR36V/GIsIlpjnPE0kXBgK0aRMlHETYhBL/+xg/5gh4QwkPGZBvcUZ/AKmM2s2dkhnwAAAAAElFTkSuQmCC" 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('data:image') == 0) {
    //base64 图片
}
else if (iconUrl.indexOf('http') < 0) {
    //相对路径的图标网址
    var domain = window.location.origin;
    iconUrl = domain + iconUrl;
}

iconUrl;