52

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.

3

4 Answers 4

148

For people still not getting the favicon with above codes;

  1. Most browsers support getting the favicon by sending a request (/favicon.ico) themselves, instead of in the html.

  2. Another solution is provided by Google.

    To get the favicon for a domain, use:
    https://s2.googleusercontent.com/s2/favicons?domain=www.stackoverflow.com

    To get the favicon for an URL, use:
    https://s2.googleusercontent.com/s2/favicons?domain_url=https://www.stackoverflow.com

7
  • 8
    This should be the correct answer.
    – Adam
    May 23, 2019 at 21:13
  • 4
    This moved to https://s2.googleusercontent.com/s2/favicons?domain=http://www.stackoverflow.com great solution. Aug 30, 2019 at 22:33
  • 4
    Note that Google's service re-encodes icons, often visibly reducing quality, sometimes for significant file size reduction but sometimes for little or none.
    – twhb
    Oct 16, 2019 at 3:33
  • How can we detect a missing icon? Google returns a globe icon and a failed Get request. Mar 25, 2022 at 22:12
  • ...also Google's services are not available world-wide, so that's a choice. Jul 21, 2022 at 10:39
36

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.

14
  • 1
    Thank you, Is there a way to get the full URL and not only /favicon.png ?
    – xRobot
    Apr 23, 2012 at 15:40
  • If you try this on stackoverflow.com for example, it wouldn't work, because of the rel="shortcut icon" attribute they used. Have a look at mine.
    – sp00m
    Apr 23, 2012 at 15:41
  • with this it does works: if((document.getElementsByTagName("link")[i].getAttribute("rel") == "icon")||(document.getElementsByTagName("link")[i].getAttribute("rel") == "shortcut icon")) . But I need the full URL and not only favicon.png :(
    – xRobot
    Apr 23, 2012 at 15:42
  • 1
    I know this is an old question, but I wanted to add something that helped me find the absolute path of the favicon, courtesy of this blog post (thingsilearned.com/2009/01/19/…). I changed favicon = nodeList[i].getAttribute("href"); to favicon = nodeList[i].href;. Ta-daaaaa! :D Jul 16, 2014 at 1:34
  • 7
    just use document.querySelector("link[rel*='icon']") Feb 11, 2018 at 22:22
11

The favicon is at /favicon.ico unless you have a <link rel="icon" href="..."> element. So you can get all of the link elements via document.getElementsByTagName and then look at each of the elements in the returned NodeList to see if any of them have the attribute rel with the value "icon" and, if so, look at its href. (You might also look at ones where rel is "shortcut icon" or "icon shortcut" for historical reasons.)

3
  • How can I get the element with rel="shortcut icon" ?
    – xRobot
    Apr 23, 2012 at 15:03
  • 1
    @xRobot: As I said, you loop through the NodeList you got back from getElementsByTagName, looking for one with rel="shortcut icon" (or just "icon", because that's the newer form). NodeList is indexed, so for instance, if you have var list = document.getElementsByTagName("link"); then list[0] is the first matched element, list[1] is the second one, etc. There's also a handy length property. See the provided links. Apr 23, 2012 at 15:08
  • @xRobot document.querySelector('link[rel="shortcut icon"]')
    – 27px
    Jun 8 at 2:47
6

Live working fiddle example: http://jsfiddle.net/sc8qp/2/

Just for good measure and completeness without regex:

function getIcons() {
    var links = document.getElementsByTagName('link');
    var icons = [];

    for(var i = 0; i < links.length; i++) {
        var link = links[i];

        //Technically it could be null / undefined if someone didn't set it!
        //People do weird things when building pages!
        var rel = link.getAttribute('rel');
        if(rel) {
            //I don't know why people don't use indexOf more often
            //It is faster than regex for simple stuff like this
            //Lowercase comparison for safety
            if(rel.toLowerCase().indexOf('icon') > -1) {
                var href = link.getAttribute('href');

                //Make sure href is not null / undefined            
                if(href) {
                    //Relative
                    //Lowercase comparison in case some idiot decides to put the 
                    //https or http in caps
                    //Also check for absolute url with no protocol
                    if(href.toLowerCase().indexOf('https:') == -1 && href.toLowerCase().indexOf('http:') == -1
                        && href.indexOf('//') != 0) {

                        //This is of course assuming the script is executing in the browser
                        //Node.js is a different story! As I would be using cheerio.js for parsing the html instead of document.
                        //Also you would use the response.headers object for Node.js below.

                        var absoluteHref = window.location.protocol + '//' + window.location.host;

                        if(window.location.port) {
                            absoluteHref += ':' + window.location.port;
                        }

                        //We already have a forward slash
                        //On the front of the href
                        if(href.indexOf('/') == 0) {
                            absoluteHref += href;
                        }
                        //We don't have a forward slash
                        //It is really relative!
                        else {
                            var path = window.location.pathname.split('/');
                            path.pop();
                            var finalPath = path.join('/');

                            absoluteHref += finalPath + '/' + href;
                        }

                        icons.push(absoluteHref);
                    }
                    //Absolute url with no protocol
                    else if(href.indexOf('//') == 0) {
                        var absoluteUrl = window.location.protocol + href;

                        icons.push(absoluteUrl);
                    }
                    //Absolute
                    else {
                        icons.push(href);
                    }
                }
            }
        }
    }

    return icons;
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.