Created
August 24, 2021 21:53
-
-
Save e111077/549d080725e4f15b06b00b46cc0796ff to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const updateMetadata = ({ | |
title, | |
description, | |
url, | |
image, | |
imageAlt | |
}: { | |
title?: string, | |
description?: string, | |
url?: string, | |
image?: string, | |
imageAlt?: string | |
}) => { | |
if (title) { | |
document.title = title; | |
setMetaTag('property', 'og:title', title); | |
} | |
if (description) { | |
setMetaTag('name', 'description', description); | |
setMetaTag('property', 'og:description', description); | |
} | |
if (image) { | |
setMetaTag('property', 'og:image', image); | |
} | |
if (imageAlt) { | |
setMetaTag('property', 'og:image:alt', imageAlt); | |
} | |
url = url || window.location.href; | |
setMetaTag('property', 'og:url', url); | |
} | |
export function setMetaTag(attrName:string, attrValue:string, content:string) { | |
let element = document.head!.querySelector(`meta[${attrName}="${attrValue}"]`); | |
if (!element) { | |
element = document.createElement('meta'); | |
element.setAttribute(attrName, attrValue); | |
document.head!.appendChild(element); | |
} | |
element.setAttribute('content', content || ''); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment