-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patharticle-dom.ts
More file actions
63 lines (53 loc) · 1.79 KB
/
article-dom.ts
File metadata and controls
63 lines (53 loc) · 1.79 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
import type { ArticleMeta } from './types';
export function findArticleElement(doc: Document) {
return (
doc.querySelector('.article-body') ??
doc.querySelector('article.tm-article-presenter__content') ??
doc.querySelector('article') ??
doc.querySelector('.tm-article-body') ??
doc.querySelector('.article-formatted-body')
);
}
export function extractMeta(doc: Document, url: string): ArticleMeta {
const title =
doc.querySelector('meta[property="og:title"]')?.getAttribute('content')?.trim() ||
doc.querySelector('h1')?.textContent?.trim() ||
'Habr Article';
const author =
doc.querySelector('meta[name="author"]')?.getAttribute('content')?.trim() ||
doc.querySelector('[rel="author"]')?.textContent?.trim() ||
undefined;
const published =
doc
.querySelector('meta[property="article:published_time"]')
?.getAttribute('content')
?.trim() ||
doc.querySelector('time')?.getAttribute('datetime')?.trim() ||
undefined;
return {
title,
author,
published,
url,
};
}
export function cleanArticle(articleEl: Element) {
const selectorsToRemove = [
'script',
'style',
'noscript',
'.tm-article-stats',
'.tm-article-snippet__stats',
'.tm-article-presentation__meta',
'.tm-article-presenter__meta',
];
selectorsToRemove.forEach((selector) => {
articleEl.querySelectorAll(selector).forEach((el) => el.remove());
});
// Obsidian does not support images wrapped in links.
articleEl.querySelectorAll('a > img').forEach((img) => {
const anchor = img.parentElement;
if (!anchor) return;
anchor.replaceWith(img);
});
}