Repository navigation
Expand file tree
/
Copy pathcontent.js
More file actions
97 lines (90 loc) · 2.91 KB
/
Copy pathcontent.js
File metadata and controls
97 lines (90 loc) · 2.91 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
(() => {
const escapeHtml = value => String(value)
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('"', '"')
.replaceAll("'", ''');
const findArticleBody = value => {
if (!value || typeof value !== 'object') {
return null;
}
if (typeof value.articleBody === 'string' && value.articleBody.trim()) {
return value.articleBody.trim();
}
for (const child of Object.values(value)) {
const articleBody = findArticleBody(child);
if (articleBody) {
return articleBody;
}
}
return null;
};
const structuredArticleBody = () => {
for (const script of document.querySelectorAll('script[type="application/ld+json"]')) {
try {
const body = findArticleBody(JSON.parse(script.textContent));
if (body) {
return body;
}
} catch {
// Ignore malformed JSON-LD and continue with Readability.
}
}
return null;
};
const siteNameFromMeta = () => {
const selectors = [
'meta[property="og:site_name"]',
'meta[name="og:site_name"]',
'meta[name="application-name"]',
'meta[name="apple-mobile-web-app-title"]',
'meta[name="publisher"]',
'meta[property="publisher"]'
];
for (const selector of selectors) {
const content = document.querySelector(selector)?.getAttribute('content')?.trim();
if (content) {
return content;
}
}
return null;
};
globalThis.html2EpubExtract = () => {
const documentClone = document.cloneNode(true);
// Ars Technica (PhotoSwipe) embeds a hidden `.pswp-caption-content` copy
// of each image caption for the lightbox alongside the visible caption
// (`figcaption` or a sibling `.caption`). Readability keeps both and
// strips class names, so this must run here — before parsing — while the
// marker class still exists. The visible caption is left untouched.
documentClone.querySelectorAll('.pswp-caption-content').forEach(caption => {
caption.remove();
});
const reader = new Readability(documentClone);
const article = reader.parse();
if (!article) {
return null;
}
const articleBody = structuredArticleBody();
if (articleBody && articleBody.length > article.textContent.length * 1.25) {
article.content = articleBody
.split(/\n+/)
.map(paragraph => paragraph.trim())
.filter(Boolean)
.map(paragraph => `<p>${escapeHtml(paragraph)}</p>`)
.join('\n');
article.textContent = articleBody;
article.length = articleBody.length;
}
return {
title: article.title,
content: article.content,
textContent: article.textContent,
byline: article.byline,
excerpt: article.excerpt,
siteName: article.siteName?.trim() || siteNameFromMeta(),
dir: article.dir,
length: article.length
};
};
})();