DEV Community

sheep
sheep

Posted on

How to Get a Website's Favicon

In the process of Chrome extension developing, I encountered an issue where loading favicons for certain pages occasionally failed. After some investigation, I discovered the root cause.

The Initial Approach

Originally, I was using Chrome's internal _favicon directory to retrieve favicons from my extension like this:

function faviconURL(pageUrl, size) {
  const url = new URL(chrome.runtime.getURL("/_favicon/"));
  url.searchParams.set('pageUrl', pageUrl);
  url.searchParams.set('size', `${size || 20}`);
  return url.toString();
}
Enter fullscreen mode Exit fullscreen mode

_favicon is a special virtual directory used internally by Chrome for handling and accessing website favicons. It's not an actual physical directory in the extension filesystem, while could be accessed via chrome.runtime.getURL("/_favicon/") with parameters:

  • pageUrl: The URL of the webpage whose favicon you want
  • size: The desired icon size in pixels (e.g., 16, 32)

This worked fine until I realized the limitation - the _favicon directory only returns cached favicons. For pages that Chrome hasn't visited yet, there would be no cached favicon available.

The Solution: Google's Public Favicon API

After some research, I found that Google provides a public API for fetching website favicons:

https://www.google.com/s2/favicons?domain=&sz=
Enter fullscreen mode Exit fullscreen mode

Parameters:

  • domain: The target domain (without http:// or https:// prefix)
  • sz: Optional icon size

This is a public API provided by Google that requires no authentication and supports cross-origin requests. By using this API, favicons even for new pages that aren't yet cached in Chrome could be displayed well.

Then my faviconURL function could be updated like this:

function faviconURL(pageUrl, size) {
  return `https://www.google.com/s2/favicons?domain=${new URL(pageUrl).hostname}&sz=${size || 20}`;
}
Enter fullscreen mode Exit fullscreen mode

This guarantees favicons will appear consistently even for those unvisited pages.

Hope you find it useful and Thanks for reading!

Top comments (0)