Status: Experimental
head-metadata is a typesafe and straightforward utility for extracting structured metadata (like <meta>, <title>, and <link>) from the <head> of an HTML document.
📖 Usage
import { extractHeadMetadata, linkExtractor, metaExtractor, titleExtractor } from 'head-metadata';
const html = `
<html>
<head>
<title>Example</title>
<meta name="description" content="An example page" />
<link rel="canonical" href="https://example.com" />
</head>
</html>
`;
const metadata = extractHeadMetadata(html, {
meta: metaExtractor,
title: titleExtractor,
link: linkExtractor
});
console.log(metadata);
You can write your own extractors to handle any <head> child element:
export const customLinkExtractor = {
type: 'collection' as const,
parent: 'link' as const,
callback: (node) => {
const rel = node.attributes.find((a) => a.local === 'rel');
const href = node.attributes.find((a) => a.local === 'href');
if (rel != null && href != null) {
return { key: rel.value, value: href.value };
}
return null;
}
} satisfies TCollectionExtractor;