Files
linker/src/lib/websiteTitle.ts
2025-06-28 00:15:51 +02:00

32 lines
796 B
TypeScript

export async function getWebsiteTitle(url: string): Promise<string | null> {
const res = await fetch(url, { redirect: "follow" })
if (!res.ok) {
return null
}
const contentType = res.headers.get("content-type")
if (!contentType || !contentType.includes("text/html")) {
return null
}
const html = await res.text()
const titleMatch = html.match(/<title[^>]*>([^<]*)<\/title>/i)
if (titleMatch && titleMatch[1]) {
const title = titleMatch[1]
.replace(/&lt;/g, "<")
.replace(/&gt;/g, ">")
.replace(/&amp;/g, "&")
.replace(/&quot;/g, "\"")
.replace(/&#39;/g, "'")
.replace(/&nbsp;/g, " ")
.trim()
return title || null
}
return null
}