refactor: Update function to handle multiple meta tags

This commit is contained in:
Gauthier Daniels 2025-04-22 12:34:54 +02:00
parent df2d18d3d9
commit a212258c07
2 changed files with 38 additions and 13 deletions

View File

@ -36,6 +36,9 @@ export default function HeadDefault() {
crossorigin="anonymous"
/>
<meta property="og:type" content="siteweb" />
<meta property="og:url" content={getCanonicalUrl()} />
<link
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&family=Lexend:wght@400;500;700&display=swap"
rel="stylesheet"

View File

@ -9,30 +9,52 @@ export const onPageTransitionEnd: OnPageTransitionEndAsync = async (
NProgress.done();
NProgress.remove();
updateCanonicalTag(pageContext);
updateCanonicalsTag(pageContext);
};
const updateCanonicalTag = (pageContext: PageContext) => {
const canonicalTag = findOrCreateCanonicalTag();
const updateCanonicalsTag = (pageContext: PageContext) => {
const canonicalNativeTag = findOrCreateTag<HTMLLinkElement>("link", {
rel: "canonical",
});
const canonicalOGTag = findOrCreateTag<HTMLMetaElement>("meta", {
property: "og:url",
});
const typeOGTag = findOrCreateTag<HTMLMetaElement>("meta", {
property: "og:type",
});
const localOGTag = findOrCreateTag<HTMLMetaElement>("meta", {
property: "og:locale",
});
const siteNameOGTag = findOrCreateTag<HTMLMetaElement>("meta", {
property: "og:site_name",
});
const canonicalUrl = buildPublicUrl(
pageContext,
pageContext.urlParsed.pathname,
);
canonicalTag.href = canonicalUrl;
canonicalNativeTag.setAttribute("href", canonicalUrl);
canonicalOGTag.setAttribute("content", canonicalUrl);
typeOGTag.setAttribute("content", "website");
localOGTag.setAttribute("content", "fr-FR");
siteNameOGTag.setAttribute("content", document.title);
};
const findOrCreateCanonicalTag = () => {
const findOrCreateTag = <T>(
tagName: string,
attributes: Record<string, string>,
): T => {
const head = document.head;
let canonicalTag: HTMLLinkElement | null = head.querySelector(
"link[rel=canonical]",
);
if (canonicalTag) return canonicalTag;
let tag: HTMLElement | null = head.querySelector(tagName);
if (tag) return tag as T;
canonicalTag = document.createElement("link");
canonicalTag.rel = "canonical";
tag = document.createElement(tagName);
for (const [key, value] of Object.entries(attributes)) {
tag.setAttribute(key, value);
}
document.head.appendChild(canonicalTag);
document.head.appendChild(tag);
return canonicalTag;
return tag as T;
};