1、需求
需要根据用户的喜好配置网页的favicon图标;
favicon图标是ico格式图片,多位32X32位
2、注意点
谷歌浏览器将其Favicon数据存储在特定的用户数据文件夹中,核心路径通常是:
```
C:\Users\<你的用户名>\AppData\Local\Google\Chrome\User Data\Default\
```
3、实现
// 1、获取到图片之后先缓存图片的 base64数据到localStroge中
const getFavicon = async (imgUrl: string, imgId: any) => {
// 通用方法:获取图片 → 转 base64 → 存缓存 → 更新 favicon
const fetchAndCacheFavicon = async (url: string, id: string) => {
try {
const res = await fetch(url)
if (!res.ok) return
const blob = await res.blob()
const reader = new FileReader()
reader.onload = () => {
const base64 = reader.result as string
localStorage.setItem('faviconId', id)
localStorage.setItem('favicon', base64)
}
reader.readAsDataURL(blob)
} catch (err) {
console.warn('获取 favicon 失败:', err)
}
}
// 空值 → 清缓存 & 设置默认
if (!imgUrl || !imgId || imgId === 'default') {
localStorage.removeItem('favicon')
localStorage.removeItem('faviconId')
return
}
const cacheId = localStorage.getItem('faviconId')
const cacheBase64 = localStorage.getItem('favicon')
// 如果缓存的 id 和当前 id 一致,直接用缓存
if (cacheId === imgId && cacheBase64) {
return
}
// 请求新的 favicon
await fetchAndCacheFavicon(imgUrl, imgId)
}
// 2、在APP.vue入口文件
getLogoAndFavicon().then(() => {
const faviconUrl = localStorage.getItem('favicon') || undefined
let link: HTMLLinkElement | null =
document.querySelector("link[rel*='icon']")
if (!link) {
link = document.createElement('link')
link.rel = 'shortcut icon'
document.head.appendChild(link)
}
link.href = faviconUrl || favicon
})
// 以上方法如果有了favicon不会再加载,如果需要强制刷新,可以删除原有的link标签,更改版本号之后再重新加载
437

被折叠的 条评论
为什么被折叠?



