From 8dc954a423f36c9a5df677b5ce1c23ee051dd147 Mon Sep 17 00:00:00 2001 From: Mohan Date: Mon, 10 Aug 2026 11:00:43 +0800 Subject: [PATCH] feat(utils): add setPageMeta for SEO --- src/utils/seo.ts | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/utils/seo.ts diff --git a/src/utils/seo.ts b/src/utils/seo.ts new file mode 100644 index 0000000..f0aa589 --- /dev/null +++ b/src/utils/seo.ts @@ -0,0 +1,32 @@ +interface PageMeta { + title?: string + description?: string + image?: string + url?: string + type?: string +} + +export function setPageMeta(meta: PageMeta) { + const siteName = 'Mach-CMS' + document.title = meta.title ? `${meta.title} | ${siteName}` : siteName + + const setTag = (selector: string, attr: string, val?: string) => { + if (!val) return + let el = document.querySelector(selector) as HTMLMetaElement | null + if (!el) { + el = document.createElement('meta') + const key = selector.includes('property=') ? 'property' : 'name' + const keyVal = selector.match(/"([^"]+)"/)?.[1] || '' + el.setAttribute(key, keyVal) + document.head.appendChild(el) + } + el.setAttribute(attr, val) + } + + setTag('meta[property="og:title"]', 'content', meta.title) + setTag('meta[property="og:description"]', 'content', meta.description) + setTag('meta[property="og:image"]', 'content', meta.image) + setTag('meta[property="og:url"]', 'content', meta.url) + setTag('meta[property="og:type"]', 'content', meta.type || 'article') + setTag('meta[name="description"]', 'content', meta.description) +} \ No newline at end of file