HTML
最简单的方式:把 <img> 标签指向 API。添加 width 和 height 以避免布局偏移。
HTML
<img src="https://favicon.is/github.com" width="32" height="32" alt="GitHub" loading="lazy">
<!-- High resolution for retina screens -->
<img src="https://favicon.is/github.com?larger=true" width="64" height="64" alt="GitHub">Markdown
在 README 文件、文档和笔记中显示网站图标。
Markdown
 [GitHub](https://github.com)CSS
将图标用作背景图片,例如显示在外部链接旁边。
CSS
a[href^="https://github.com"]::before {
content: "";
display: inline-block;
width: 1em;
height: 1em;
margin-right: 0.35em;
vertical-align: -0.125em;
background: url("https://favicon.is/github.com?size=32") center / contain no-repeat;
}JavaScript
在运行时为页面上的所有外部链接添加图标。
JavaScript
document.querySelectorAll('a[href^="http"]').forEach((link) => {
const { hostname } = new URL(link.href);
const icon = document.createElement('img');
icon.src = `https://favicon.is/${hostname}?size=32`;
icon.width = icon.height = 16;
icon.alt = '';
icon.loading = 'lazy';
icon.style.marginRight = '0.35em';
link.prepend(icon);
});React
一个小巧的可复用组件,图片加载失败时自动回退。
React
export function Favicon({ domain, size = 16 }) {
return (
<img
src={`https://favicon.is/${domain}?size=${size * 2}`}
width={size}
height={size}
alt=""
loading="lazy"
onError={(event) => {
event.currentTarget.src = 'https://favicon.is/default-favicon.svg';
}}
/>
);
}
// <Favicon domain="github.com" />Vue
同样的组件,以 Vue 单文件组件的形式实现。
Vue
<script setup>
defineProps({
domain: { type: String, required: true },
size: { type: Number, default: 16 },
});
</script>
<template>
<img
:src="`https://favicon.is/${domain}?size=${size * 2}`"
:width="size"
:height="size"
alt=""
loading="lazy"
/>
</template>Python
在脚本中下载图标,例如用来制作书签页面。
Python
import pathlib
import urllib.request
domains = ["github.com", "wikipedia.org", "python.org"]
out = pathlib.Path("icons")
out.mkdir(exist_ok=True)
for domain in domains:
with urllib.request.urlopen(f"https://favicon.is/{domain}?larger=true") as response:
ext = {"image/png": "png", "image/x-icon": "ico", "image/svg+xml": "svg"}.get(
response.headers.get_content_type(), "img"
)
(out / f"{domain}.{ext}").write_bytes(response.read())
print(domain, response.headers["X-Source"])PHP
在服务端模板中渲染图标。
PHP
<?php
$domain = parse_url($link, PHP_URL_HOST);
$src = 'https://favicon.is/' . rawurlencode($domain) . '?size=32';
?>
<img src="<?= htmlspecialchars($src) ?>" width="16" height="16" alt="">Go
获取图标并保存到磁盘。
Go
package main
import (
"io"
"net/http"
"os"
)
func main() {
resp, err := http.Get("https://favicon.is/go.dev?larger=true")
if err != nil {
panic(err)
}
defer resp.Body.Close()
file, err := os.Create("go.dev.png")
if err != nil {
panic(err)
}
defer file.Close()
if _, err := io.Copy(file, resp.Body); err != nil {
panic(err)
}
}cURL
在命令行中查看响应头。
cURL
# Inspect the response headers
curl -I https://favicon.is/github.com
# Save a 64 px icon
curl -o github.png "https://favicon.is/github.com?size=64"