47 lines
2.3 KiB
JavaScript
47 lines
2.3 KiB
JavaScript
// Läuft in der Seite: Hauptinhalt per Readability, Ausgabe als Markdown per Turndown.
|
|
function extract() {
|
|
const td = new TurndownService({ headingStyle: "atx", codeBlockStyle: "fenced", bulletListMarker: "-" });
|
|
td.use(turndownPluginGfm.gfm);
|
|
// als Regel, damit sie vor der eingebauten Regel für Bilder greift
|
|
td.addRule("drop", {
|
|
filter: ["script", "style", "noscript", "iframe", "svg", "img", "picture", "video", "audio", "canvas", "template"],
|
|
replacement: () => "",
|
|
});
|
|
|
|
// auf einer Kopie arbeiten, die Seite selbst bleibt unverändert
|
|
const doc = document.cloneNode(true);
|
|
// Cookie und Consent Banner, aber nichts, was den Hauptinhalt umschließt
|
|
doc.querySelectorAll("[id*=cookie i], [class*=cookie i], [id*=consent i], [class*=consent i]").forEach((e) => {
|
|
if (e !== doc.documentElement && e !== doc.body && !e.querySelector("main, article")) e.remove();
|
|
});
|
|
|
|
// Readability sucht einen einzelnen Artikel und verändert sein Dokument, daher eine eigene Kopie
|
|
let art = null;
|
|
try {
|
|
art = new Readability(doc.cloneNode(true), { serializer: (el) => el }).parse();
|
|
} catch (e) {}
|
|
|
|
// ganze Seite ohne Menüs, Formulare und Fußzeile
|
|
const page = doc.body;
|
|
if (page) {
|
|
page.querySelectorAll("script, style, noscript, template, nav, footer, form, dialog, [role=navigation], [role=contentinfo], [aria-hidden=true]")
|
|
.forEach((e) => e.remove());
|
|
page.querySelectorAll("a[href]").forEach((a) => a.setAttribute("href", a.href));
|
|
}
|
|
|
|
// Der Artikel gilt nur, wenn er den Großteil des Seitentextes abdeckt.
|
|
// Auf Seiten mit mehreren gleichwertigen Abschnitten würde sonst alles bis auf einen fehlen.
|
|
const size = (n) => (n ? n.textContent.replace(/\s+/g, " ").trim().length : 0);
|
|
const useArticle = art && art.content && size(art.content) >= 200 && size(art.content) >= 0.7 * size(page);
|
|
const node = useArticle ? art.content : page;
|
|
const title = ((useArticle && art.title) || document.title).trim();
|
|
|
|
let markdown = "";
|
|
try {
|
|
if (node) markdown = td.turndown(node);
|
|
} catch (e) {}
|
|
// z.B. wenn die Seite das Umbauen von HTML verbietet
|
|
if (!markdown.trim() && document.body) markdown = document.body.innerText;
|
|
|
|
return { url: location.href, title, markdown: markdown.replace(/\n{3,}/g, "\n\n").trim() };
|
|
} |