How to get favicon's URL from a generic webpage in Javascript?
For people still not getting the favicon with above codes;
Most browsers support getting the favicon by sending a request (
/favicon.ico
) themselves, instead of in the html.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
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.
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.)