Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[RFC] useFavicon Hook (with ICO/SVG/PNG/GIF Support) #581

Closed
linbudu599 opened this issue Aug 11, 2020 · 3 comments
Closed

[RFC] useFavicon Hook (with ICO/SVG/PNG/GIF Support) #581

linbudu599 opened this issue Aug 11, 2020 · 3 comments
Assignees
Labels
feature New feature or request

Comments

@linbudu599
Copy link
Contributor

import { useEffect } from 'react';

// image/vnd.microsoft.icon MIME类型只有当图像真的是ICO文件时才会起作用
// image/x-icon 会同时也适用于位图与GIF
// 主要是为了兼容扩展名为ico的非ico文件
const ImgTypeMap = {
  SVG: 'image/svg+xml',
  ICO: 'image/x-icon',
  GIF: 'image/gif',
  PNG: 'image/png'
};

type ImgTypes = keyof typeof ImgTypeMap;

const useFavicon = (favUrl: string): void => {
  const cutUrl = favUrl.split('.');
  const imgSuffix = cutUrl[cutUrl.length - 1].toLocaleUpperCase() as ImgTypes;

  useEffect(() => {
    const link: HTMLLinkElement =
      document.querySelector("link[rel*='icon']") ||
      document.createElement('link');

    link.type = ImgTypeMap[imgSuffix];
    link.href = favUrl;
    // 大部分浏览器只会识别icon 只有IE会识别整个名称
    link.rel = 'shortcut icon';

    document.getElementsByTagName('head')[0].appendChild(link);
  }, [favUrl]);
};

export default useFavicon;
@awmleer awmleer added the feature New feature or request label Aug 11, 2020
@awmleer
Copy link
Collaborator

awmleer commented Aug 11, 2020

可以参考下 React Helmet

@linbudu599
Copy link
Contributor Author

我理解是 命令式的useFavicon 在切换页面时实现favicon随着切换更友好些233 而且通常来说useTitle + useFavicon就能满足普通用户需求了

@awmleer
Copy link
Collaborator

awmleer commented Aug 31, 2020

我理解是 命令式的useFavicon 在切换页面时实现favicon随着切换更友好些233 而且通常来说useTitle + useFavicon就能满足普通用户需求了

嗯嗯 +1
Hooks 形态的 useFavicon 和组件形态的 React Helmet 的确还是适用场景不太一样的,欢迎 PR~ @linbudu599

@awmleer awmleer self-assigned this Aug 31, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature New feature or request
Projects
None yet
Development

No branches or pull requests

3 participants