UNPKG

common-hook

Version:
27 lines (26 loc) 737 B
import { useEffect } from "react"; const ImgTypeMap = { SVG: "image/svg+xml", ICO: "image/x-icon", GIF: "image/gif", PNG: "image/png" }; /** * @name 设置页面favicon * @example * useFavicon(url) */ export const useFavicon = (href) => { useEffect(() => { if (!href) return; const cutUrl = href.split("."); const imgSuffix = cutUrl[cutUrl.length - 1].toLocaleUpperCase(); const link = document.querySelector("link[rel*='icon']") || document.createElement("link"); link.type = ImgTypeMap[imgSuffix]; link.href = href; link.rel = "shortcut icon"; document.getElementsByTagName("head")[0].appendChild(link); }, [href]); };