提取社交分享圖片和 Open Graph 標簽
Bun 的 HTMLRewriter API 可用於高效地從 HTML 內容提取社交分享圖片和 Open Graph 元數據。這對於構建鏈接預覽功能、社交媒體卡片或網絡抓取器特別有用。我們可以使用 HTMLRewriter 將 CSS 選擇器匹配到我們要處理的 HTML 元素、文本和屬性。
ts
interface SocialMetadata {
title?: string;
description?: string;
image?: string;
url?: string;
siteName?: string;
type?: string;
}
async function extractSocialMetadata(url: string): Promise<SocialMetadata> {
const metadata: SocialMetadata = {};
const response = await fetch(url);
const rewriter = new HTMLRewriter()
// 提取 Open Graph meta 標簽
.on('meta[property^="og:"]', {
element(el) {
const property = el.getAttribute("property");
const content = el.getAttribute("content");
if (property && content) {
// 將 "og:image" 轉換為 "image" 等
const key = property.replace("og:", "") as keyof SocialMetadata;
metadata[key] = content;
}
},
})
// 提取 Twitter Card meta 標簽作為後備
.on('meta[name^="twitter:"]', {
element(el) {
const name = el.getAttribute("name");
const content = el.getAttribute("content");
if (name && content) {
const key = name.replace("twitter:", "") as keyof SocialMetadata;
// 僅當我們沒有 OG 數據時才使用 Twitter Card 數據
if (!metadata[key]) {
metadata[key] = content;
}
}
},
})
// 回退到常規 meta 標簽
.on('meta[name="description"]', {
element(el) {
const content = el.getAttribute("content");
if (content && !metadata.description) {
metadata.description = content;
}
},
})
// 回退到 title 標簽
.on("title", {
text(text) {
if (!metadata.title) {
metadata.title = text.text;
}
},
});
// 處理響應
await rewriter.transform(response).blob();
// 將相對圖片 URL 轉換為絕對 URL
if (metadata.image && !metadata.image.startsWith("http")) {
try {
metadata.image = new URL(metadata.image, url).href;
} catch {
// 如果解析失敗,保留原始 URL
}
}
return metadata;
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
ts
// 示例用法
const metadata = await extractSocialMetadata("https://bun.com");
console.log(metadata);
// {
// title: "Bun — A fast all-in-one JavaScript runtime",
// description: "Bundle, transpile, install and run JavaScript & TypeScript projects — all in Bun. Bun is a fast all-in-one JavaScript runtime & toolkit designed for speed, complete with a bundler, test runner, and Node.js-compatible package manager.",
// image: "https://bun.com/share.jpg",
// type: "website",
// ...
// }1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10