xRobot xRobot - 1 month ago 10
Javascript Question

How to get favicon's URL from a generic webpage in Javascript?

I need a way to get the favicon's URL from a generic webpage considering that the favicon is not always at the base url.

P.s. without using an external service or library.

Answer Source

This seems to work:

var getFavicon = function(){
    var favicon = undefined;
    var nodeList = document.getElementsByTagName("link");
    for (var i = 0; i < nodeList.length; i++)
    {
        if((nodeList[i].getAttribute("rel") == "icon")||(nodeList[i].getAttribute("rel") == "shortcut icon"))
        {
            favicon = nodeList[i].getAttribute("href");
        }
    }
    return favicon;        
}

alert(getFavicon());‚Äč

Or have a look at http://jsfiddle.net/PBpgY/3/ for an online example.