首页 > 解决方案 > 不在标准位置时如何找到图标

问题描述

这是我的链接页面的一部分: 网站名称,每个名称前面都有其网站图标

使用以下代码插入各个图标:

<script> "use strict"
    let anchors = document.getElementsByTagName("a")
    for (let a=0; a<anchors.length; ++a) {
        if ("undefined" !== typeof anchors[a].href) {
            let d = document.createElement("div")
            let i = document.createElement("img")
            i.setAttribute("alt", "")
            i.setAttribute("class", "favicon")
            i.setAttribute("src", anchors[a].href.replace(/^(.*:\/\/[^\/]*).*/, "$1"+"/favicon.ico"))
            d.appendChild(i)
            d.setAttribute("class", "logo")
            anchors[a].insertBefore(d, anchors[a].childNodes[0])
        }
    }
    window.onload = function() {
        let images = document.getElementsByTagName("img")
        for (let i=0; i<anchors.length; ++i)
            if ( (typeof images[i].naturalWidth !== "undefined") && (images[i].naturalWidth === 0) )
                images[i].src = ".Images/Oops.svg"
    }
</script>

问题是,一些网站,例如DuolingoGoogle/Webmasterfavicon.ico在它们的根目录中没有。

除了在我自己的网站上手动获取和存储它们的副本之外,有没有办法为标准位置<img src="…&quot; />中缺少的网站找到合适的 URL favicon.ico

标签: javascriptfavicon

解决方案


你可以从

<link rel="icon"              href="path_to_favicon">
<link rel="apple-touch-icon"  href="path_to_favicon">

Javascript:

function get_favicon() {
    let links = document.getElementsByTagName("link");
    for(let a=0; a < links.length; a++) {
        let link = links[a];
        let attr = link.getAttribute("rel");
        if(attr == "icon" || attr == "apple-touch-icon" || attr == "mask-icon" || attr == "shortcut icon") {
            return link.getAttribute("href");
        }
    }
}

这并不详尽,但您可以设置这个额外层来推断网站图标的位置。


推荐阅读