Skip to content

Instantly share code, notes, and snippets.

@e111077
Created August 24, 2021 21:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save e111077/549d080725e4f15b06b00b46cc0796ff to your computer and use it in GitHub Desktop.
Save e111077/549d080725e4f15b06b00b46cc0796ff to your computer and use it in GitHub Desktop.
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