我有一个简单的react-hook应用程序,它使用next.js,我尝试动态更新收藏夹图标。所以在我的 index.js 中我:
import React from "react";
import Head from "next/head";
import { useTheme } from "@emotion/react";
export default function Home() {
const theme = useTheme();
return (
<>
<Head>
<link id="favicon" rel="shortcut icon" type="image/png" href={theme.images.favicon} />
</Head>
<HomePage />
</>
);
}
这在 Firefox、Chrome 和 Edge 上运行良好,但在 safari 上运行不佳,我仍然从 /public/favicon.ico 获取默认图标。
我上网查了一下,看到了不同的解决方案。所以首先我尝试设置不同的链接(https://css-tricks.com/favicon-quiz/):
<link rel="apple-touch-icon" sizes="57x57" href={theme.images.favicon} />
<link rel="apple-touch-icon" sizes="114x114" href={theme.images.favicon} />
<link rel="apple-touch-icon" sizes="72x72" href={theme.images.favicon} />
<link rel="apple-touch-icon" sizes="144x144" href={theme.images.favicon} />
<link rel="apple-touch-icon" sizes="60x60" href={theme.images.favicon} />
<link rel="apple-touch-icon" sizes="120x120" href={theme.images.favicon} />
<link rel="apple-touch-icon" sizes="76x76" href={theme.images.favicon} />
<link rel="apple-touch-icon" sizes="152x152" href={theme.images.favicon} />
但什么都没有改变。
我尝试使用 use-favicon 钩子(https://bit.dev/giladshoham/react-hooks/use/use-favicon):
import React from "react";
import Head from "next/head";
import { useTheme } from "@emotion/react";
import {useFavicon} from 'react-use';
export default function Home() {
const theme = useTheme();
useFavicon({theme.images.favicon});
return (
<>
<HomePage />
</>
);
}
我看到这个钩子的演示:https://www.npmjs.com/package/react-favicon在 safari 上不起作用。
看起来 safari 只接受默认的图标,我不知道如何使用其他地方的图标。
我确实错过了一些东西,希望你能帮助我。
提前谢谢。
====编辑====
我忘了提一些可能很重要的事情。我也在使用 Next.js
将 Head 元素移动到 _app.js 文件后,我开始在 safari 上看到该图标。
import React from "react";
import Head from "next/head";
const faviconUrl = "myUrl";
export default function MyApp() {
return (
<>
<Head>
<link rel="icon shortcut " href={faviconUrl} />
<link rel="apple-touch-icon" href={faviconUrl} />
</Head>
</>
);
}
但是我仍然没有找到任何方法来动态更新 safari 上的 favIcon,但看起来这是不可能的。 参考:无法在 safari 中使用 javascript 更改图标
示例:https://mathiasbynens.be/demo/dynamic-favicons
感谢您的帮助。
在 NextJS 中,您可以通过将图标绑定到状态来动态更改图标,例如:
<Head>
{ showOtherFavicon
? <link rel="icon" href="./logos/favicon_2.png" />
: <link rel="shortcut icon" href="./logos/favicon_1.png" />
}
</Head>
favicon 文件放在
/public
目录下。
对于create-react-app,您需要使用react-helmet,但由于它是一个单页应用程序,因此它不由SEO处理。
如果您在浏览器中没有看到图标更新,您可以清空缓存,有时即使刷新页面也不会反映更新。
您可以使用 React Helmet 来实现此目的。 [https://www.npmjs.com/package/react-helmet][1]
import React from "react";
import { Helmet } from "react-helmet";
import { useTheme } from "@emotion/react";
export default function Home() {
const theme = useTheme();
return (
<>
<Helmet>
<link
rel="shortcut icon"
type="image/jpg"
href={theme.images.favicon}
/>
<HomePage />
</>
);
}
[1]: https://www.npmjs.com/package/react-helmet