/** * useSeo — dynamically updates document and meta tags on route change. * * Usage: * const seo = useSeo() * // On page mount / watch: * watch(route, () => { * seo.set({ title: 'Min sida', description: '...' }) * }) * * The composable sets <title>, meta[name=description], meta[name=keywords], * meta[property=og:title], meta[property=og:description], meta[name=twitter:title], * and meta[name=twitter:description]. */ export interface SeoMeta { title: string description: string keywords?: string ogTitle?: string ogDescription?: string canonical?: string } export function useSeo() { function set(meta: SeoMeta) { const title = meta.title ?? 'Bilhej' const description = meta.description ?? 'Skicka brev till fordonsägare via registreringsnummer.' // Document title document.title = title // Common meta tags updateMeta('description', description) if (meta.keywords) updateMeta('keywords', meta.keywords) // Open Graph updateMeta('og:title', meta.ogTitle ?? title, 'property') updateMeta('og:description', meta.ogDescription ?? description, 'property') // Twitter updateMeta('twitter:title', meta.ogTitle ?? title, 'name') updateMeta('twitter:description', meta.ogDescription ?? description, 'name') // Canonical URL updateCanonical(meta.canonical) } function reset() { document.title = 'Bilhej — Skicka brev till fordonsägare' updateMeta( 'description', 'Skicka ett fysiskt brev till en fordonsägare via registreringsnummer.', ) updateMeta('og:title', 'Bilhej — Skicka brev till fordonsägare', 'property') updateMeta( 'og:description', 'Skicka ett fysiskt brev till en fordonsägare via registreringsnummer.', 'property', ) updateCanonical('https://bilhej.se/') } return { set, reset } } function updateMeta( nameOrProperty: string, content: string, attr: 'name' | 'property' = 'name', ) { let el = document.querySelector( `meta[${attr}="${nameOrProperty}"]`, ) as HTMLMetaElement | null if (!el) { el = document.createElement('meta') el.setAttribute(attr, nameOrProperty) document.head.appendChild(el) } el.setAttribute('content', content) } function updateCanonical(href: string | undefined) { let link = document.querySelector( 'link[rel="canonical"]', ) as HTMLLinkElement | null if (!link) { link = document.createElement('link') link.setAttribute('rel', 'canonical') document.head.appendChild(link) } link.setAttribute('href', href ?? 'https://bilhej.se/') }