You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Favicon抓取API设置自定义降级图片及多级降级逻辑?

三级Favicon降级逻辑实现方案(Vue.js)

完全可以实现你需要的三级降级逻辑,核心思路是通过监听图片的加载错误事件,依次切换Favicon的数据源,直到加载成功或触发最终的降级图片。

实现步骤

  • 初始化优先级最高的数据源:默认使用Google S2或DuckDuckGo的API地址
  • 监听加载错误事件:第一次加载失败时,切换到自有Favicon抓取API
  • 二次错误处理:如果自有API也加载失败,直接切换到本地自定义降级图片

代码示例

可以封装成一个可复用的Vue组件:

<template>
  <img
    :src="currentFaviconUrl"
    :alt="domain + ' favicon'"
    @error="handleFaviconError"
    class="favicon"
  />
</template>

<script setup>
import { ref } from 'vue';

const props = defineProps({
  domain: {
    type: String,
    required: true
  }
});

// 定义数据源优先级顺序
const faviconSources = ref([
  // 1. 优先使用Google S2 API
  `https://www.google.com/s2/favicons?domain=${props.domain}&sz=64`,
  // 2. 自有API(替换成你的实际接口地址)
  `https://your-custom-api.com/favicon?domain=${props.domain}`,
  // 3. 自定义降级图片(本地资源或固定地址)
  '/assets/default-favicon.png'
]);

const currentSourceIndex = ref(0);
const currentFaviconUrl = ref(faviconSources.value[currentSourceIndex.value]);

const handleFaviconError = () => {
  // 未到最后一个数据源时,切换到下一个
  if (currentSourceIndex.value < faviconSources.value.length - 1) {
    currentSourceIndex.value++;
    currentFaviconUrl.value = faviconSources.value[currentSourceIndex.value];
  }
};
</script>

<style scoped>
.favicon {
  width: 32px;
  height: 32px;
  border-radius: 4px;
}
</style>

关键说明

  • 按优先级把数据源存入数组,Google/DuckDuckGo在前,自有API居中,降级图片最后
  • @error事件会在图片加载失败时触发,每次失败自动切换到下一个数据源
  • 若所有数据源都失败,最终会停留在自定义降级图片上(不再触发切换逻辑)
  • 可根据需求调整API参数,比如Google S2的sz参数可控制图标尺寸

内容的提问来源于stack exchange,提问作者M Atif Mehmood

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 17:11:07