ai-chatbot/components/favicon-updater.tsx
Your Name d05167103b
Some checks failed
Lint / build (20) (push) Has been cancelled
Playwright Tests / test (push) Has been cancelled
修复网站设置favicon不生效与缓存命中默认图标
2026-02-14 21:30:06 +08:00

63 lines
1.5 KiB
TypeScript

"use client";
import { useEffect } from "react";
export function FaviconUpdater() {
useEffect(() => {
let isDisposed = false;
const timestamp = Date.now();
const urlWithCache = `/api/favicon?v=${timestamp}`;
Promise.resolve().then(() => {
if (isDisposed) {
return;
}
const managedSelector =
'link[rel="icon"],link[rel="shortcut icon"],link[rel="apple-touch-icon"]';
const existingLinks = document.querySelectorAll<HTMLLinkElement>(
managedSelector
);
existingLinks.forEach((link) => {
link.href = urlWithCache;
link.setAttribute("data-managed-favicon", "true");
if (link.rel === "icon") {
link.type = "image/x-icon";
link.setAttribute("sizes", "any");
}
});
const ensureLink = (rel: string, type?: string) => {
let link = document.querySelector(
`link[rel="${rel}"]`
) as HTMLLinkElement | null;
if (!link) {
link = document.createElement("link");
link.rel = rel;
document.head.appendChild(link);
}
link.href = urlWithCache;
link.setAttribute("data-managed-favicon", "true");
if (type) {
link.type = type;
}
if (rel === "icon") {
link.setAttribute("sizes", "any");
}
};
ensureLink("icon", "image/x-icon");
ensureLink("apple-touch-icon");
ensureLink("shortcut icon");
});
return () => {
isDisposed = true;
};
}, []);
return null;
}