use-app-favicon.ts 1.0 KB

123456789101112131415161718192021222324
  1. import { useAsyncEffect } from 'ahooks'
  2. import { appDefaultIconBackground } from '@/config'
  3. import { searchEmoji } from '@/utils/emoji'
  4. export function useAppFavicon(enable: boolean, icon?: string, icon_background?: string) {
  5. useAsyncEffect(async () => {
  6. if (!enable)
  7. return
  8. const link: HTMLLinkElement = document.querySelector('link[rel*="icon"]') || document.createElement('link')
  9. // eslint-disable-next-line prefer-template
  10. link.href = 'data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22>'
  11. + '<rect width=%22100%25%22 height=%22100%25%22 fill=%22' + encodeURIComponent(icon_background || appDefaultIconBackground) + '%22 rx=%2230%22 ry=%2230%22 />'
  12. + '<text x=%2212.5%22 y=%221em%22 font-size=%2275%22>'
  13. + (icon ? await searchEmoji(icon) : '🤖')
  14. + '</text>'
  15. + '</svg>'
  16. link.rel = 'shortcut icon'
  17. link.type = 'image/svg'
  18. document.getElementsByTagName('head')[0].appendChild(link)
  19. }, [enable, icon, icon_background])
  20. }