Page to Markdown, a bookmarklet that turns articles into clean Markdown
Page to Markdown is a bookmarklet I wrote that turns the article on any page, or just the selected text, into clean Markdown with front matter and footnotes. It runs inside the browser and sends nothing anywhere.
Page to Markdown turns the article on the current page into Markdown, inside the browser. Nothing is sent to a server, so it also works on pages behind a login.1
What it does:
- finds the article and leaves out menus, sidebars, share buttons, comment sections and anything hidden;2
- with text selected, converts only the selection;
- keeps headings, nested lists, tables, code blocks with their language, quotes, images, figures and task lists;
- turns relative links into full addresses;
- turns footnotes into Markdown footnotes,
[^1]in the text and the notes at the end;3 - adds front matter with the title, the source and the dates, which a checkbox switches off.4
The result opens in a panel where it can still be edited, with buttons to copy it or download it as a .md file. Esc closes it.
It runs the same way as Font Peek: paste it into the developer console, or create a bookmark and put javascript: followed by the whole file in the address field.
/*
Page to Markdown
by Pablo Murad · https://pablomurad.com
Turns the article on the current page (or just the text you selected) into
clean Markdown, right in the browser. Nothing is sent anywhere.
Edit the result in the panel, then copy it or download it as a .md file.
Esc closes. Run it again to toggle.
*/
(() => {
const ID = "page-to-md-root";
const old = document.getElementById(ID);
if (old) { old.__close(); return; }
const abs = url => {
if (!url) return "";
try {
const u = new URL(url.trim(), document.baseURI);
return /^(https?|mailto|ftp|data):$/.test(u.protocol) ? u.href : "";
} catch (e) { return ""; }
};
/* Elements that never carry article text. */
const DROP = new Set(["SCRIPT", "STYLE", "NOSCRIPT", "TEMPLATE", "IFRAME", "SVG", "CANVAS",
"FORM", "INPUT", "BUTTON", "SELECT", "TEXTAREA", "OBJECT", "EMBED", "DIALOG", "LINK", "META"]);
/* Page furniture, skipped when converting a whole page (kept inside a selection). */
const CLUTTER = /(^|[\s_-])(share|sharing|social|comments?|related|reactions|likes|webmentions?|syndication|advert|ads?|promo|newsletter|subscribe|cookie|breadcrumbs?|sidebar|popup|modal|banner)([\s_-]|$)/i;
/* Footnote lists. Some sites hide them and show the notes in the margin
instead, so they are kept even when hidden. */
const NOTES = "section.footnotes, div.footnotes, .footnotes > ol, [role=doc-endnotes], ol.references";
const selection = getSelection();
const fromSelection = !!(selection && selection.rangeCount && selection.toString().trim());
const skip = el => {
if (DROP.has(el.tagName.toUpperCase())) return true;
if (el.matches(NOTES)) return false;
if (el.hidden || el.getAttribute("aria-hidden") === "true") return true;
if (fromSelection) return false;
const tag = el.tagName;
if (tag === "NAV" || tag === "ASIDE") return true;
const role = el.getAttribute("role");
if (role && /^(navigation|complementary|banner|contentinfo|search)$/.test(role)) return true;
if ((tag === "HEADER" || tag === "FOOTER") && !el.closest("article")) return true;
const hook = `${el.id} ${typeof el.className === "string" ? el.className : ""}`;
if (CLUTTER.test(hook) && !el.querySelector("h1")) return true;
if (el.isConnected) {
const cs = getComputedStyle(el);
if (cs.display === "none" || cs.visibility === "hidden") return true;
}
return false;
};
/* Find the element that holds the article. Every block of real prose counts
toward its containers; reader modes use a fancier version of the same idea. */
const findRoot = () => {
const prose = [...document.body.querySelectorAll("p, pre, blockquote, dd, li")]
.filter(el => el.textContent.trim().length >= 25 && !el.closest("nav, aside, footer, [role=navigation]"));
const total = el => prose.reduce((n, p) => n + (el.contains(p) ? p.textContent.length : 0), 0);
const known = [...document.querySelectorAll(
"article, main, [role=main], [itemprop=articleBody], .post-content, .entry-content, .article-body, #content")];
const sized = known.map(el => [el, total(el)]).filter(([, n]) => n >= 400);
if (sized.length) {
const most = Math.max(...sized.map(([, n]) => n));
/* The innermost container that still holds nearly all of the text. */
const fits = sized.filter(([, n]) => n >= most * 0.85).map(([el]) => el);
return fits.find(el => !fits.some(o => o !== el && el.contains(o))) || fits[0];
}
const score = new Map();
for (const p of prose) {
const el = p.parentElement;
if (el) score.set(el, (score.get(el) || 0) + p.textContent.length);
}
let best = null, bestScore = 0;
for (const [el, n] of score) if (n > bestScore) { best = el; bestScore = n; }
if (!best || bestScore < 200) return document.body;
/* Climb while the parent holds clearly more prose (several sections, not one). */
let current = best, size = total(best);
while (current.parentElement && current.parentElement !== document.body) {
const up = total(current.parentElement);
if (up < size * 1.25) break;
current = current.parentElement; size = up;
}
return current;
};
const escText = s => s
.replace(/\\/g, "\\\\")
.replace(/([*`\[\]<])/g, "\\$1")
.replace(/(^|\s)_/g, "$1\\_")
.replace(/_(\s|$)/g, "\\_$1");
const fence = (text, min) => {
const runs = text.match(/`+/g) || [];
const longest = runs.reduce((m, r) => Math.max(m, r.length), 0);
return "`".repeat(Math.max(min, longest + 1));
};
const inlineCode = text => {
const f = fence(text, 1);
const pad = /^`|`$/.test(text) ? " " : "";
return `${f}${pad}${text}${pad}${f}`;
};
const wrap = (mark, inner) => {
if (/\n\s*\n/.test(inner)) return inner; /* bold or italic around whole blocks: leave it plain */
const m = inner.match(/^(\s*)([\s\S]*?)(\s*)$/);
return m[2] ? `${m[1]}${mark}${m[2]}${mark}${m[3]}` : inner;
};
const block = s => `\n\n${s.trim()}\n\n`;
const imageSrc = img => abs(img.currentSrc || img.getAttribute("src") ||
img.getAttribute("data-src") || img.getAttribute("data-original") ||
(img.getAttribute("srcset") || "").split(/\s+/)[0]);
const children = (node, ctx) => [...node.childNodes].map(n => conv(n, ctx)).join("");
const list = (el, ctx) => {
const ordered = el.tagName === "OL";
let n = parseInt(el.getAttribute("start") || "1", 10) || 1;
const tight = [...el.children].every(li => !li.querySelector("p, pre, blockquote, table"));
const items = [];
for (const li of el.children) {
if (li.tagName !== "LI") continue;
const marker = ordered ? `${n++}. ` : "- ";
const box = li.querySelector(":scope > input[type=checkbox]");
const task = box ? (box.checked ? "[x] " : "[ ] ") : "";
let body = children(li, ctx).trim().replace(/\n{3,}/g, "\n\n");
if (tight) body = body.replace(/\n\n+/g, "\n");
const indent = " ".repeat(marker.length);
items.push(marker + task + body.split("\n").map((l, i) => i && l ? indent + l : l).join("\n"));
}
return block(items.join(tight ? "\n" : "\n\n"));
};
const table = (el, ctx) => {
const rows = [...el.rows].map(r => [...r.cells].map(c =>
children(c, ctx).trim().replace(/\s*\n+\s*/g, " ").replace(/\|/g, "\\|") || " "));
if (!rows.length) return "";
const width = Math.max(...rows.map(r => r.length));
rows.forEach(r => { while (r.length < width) r.push(" "); });
const line = r => `| ${r.join(" | ")} |`;
const [head, ...body] = rows;
return block([line(head), line(head.map(() => "---")), ...body.map(line)].join("\n"));
};
/* Footnotes become Markdown footnotes: [^1] in the text, [^1]: at the end. */
const label = (text, id) => {
const t = text.replace(/[\[\]\s]/g, "");
return /^\w{1,12}$/.test(t) ? t : ((id || "").match(/(\d+)$/) || [])[1] || "";
};
const noteRef = el => {
const a = el.tagName === "A" ? el : el.tagName === "SUP" && el.children.length === 1 ? el.querySelector(":scope > a") : null;
if (!a || !/^#/.test(a.getAttribute("href") || "")) return "";
const isRef = a.getAttribute("role") === "doc-noteref" || /footnote|fn-?ref|noteref/i.test(a.className) || el.tagName === "SUP";
return isRef && a.textContent.trim().length <= 6 ? label(a.textContent, a.getAttribute("href")) : "";
};
const isBacklink = a => a.getAttribute("role") === "doc-backlink" || /back/i.test(a.className) ||
/^[↩↑^⤴\s]+$/.test(a.textContent) || /^#(fnref|cite_ref)/.test(a.getAttribute("href") || "");
const notes = (el, ctx) => {
const items = [...el.querySelectorAll("li")].filter(li => li.id);
if (!items.length) return "";
return block(items.map((li, i) => {
const text = children(li, ctx).trim().replace(/\n{2,}/g, "\n\n ").replace(/\s*\\$/, "");
return `[^${label("", li.id) || i + 1}]: ${text}`;
}).join("\n\n"));
};
const conv = (node, ctx = {}) => {
if (node.nodeType === 3) {
if (ctx.pre) return node.nodeValue;
return escText(node.nodeValue.replace(/\s+/g, " "));
}
if (node.nodeType === 11) return children(node, ctx);
if (node.nodeType !== 1 || skip(node)) return "";
const el = node, tag = el.tagName.toUpperCase();
if (el.matches(NOTES)) return notes(el, ctx);
const ref = noteRef(el);
if (ref) return `[^${ref}]`;
switch (tag) {
case "H1": case "H2": case "H3": case "H4": case "H5": case "H6": {
const text = children(el, ctx).replace(/\s+/g, " ").trim();
return text ? block("#".repeat(+tag[1]) + " " + text) : "";
}
case "P": return block(children(el, ctx));
case "BR": return ctx.pre ? "\n" : "\\\n";
case "HR": return block("---");
case "STRONG": case "B": return wrap("**", children(el, ctx));
case "EM": case "I": case "CITE": return wrap("*", children(el, ctx));
case "DEL": case "S": case "STRIKE": return wrap("~~", children(el, ctx));
case "MARK": return wrap("==", children(el, ctx));
case "CODE": case "KBD": case "SAMP":
return ctx.pre ? el.textContent : inlineCode(el.textContent);
case "PRE": {
const code = el.querySelector("code") || el;
const hint = `${code.className} ${el.className}`;
const lang = (hint.match(/(?:language|lang)-([\w+#-]+)/) || [])[1] ||
el.getAttribute("data-lang") || code.getAttribute("data-lang") || "";
const text = el.textContent.replace(/\n$/, "");
const f = fence(text, 3);
return block(`${f}${lang}\n${text}\n${f}`);
}
case "BLOCKQUOTE": {
const inner = children(el, ctx).trim().replace(/\n{3,}/g, "\n\n");
return inner ? block(inner.split("\n").map(l => l ? "> " + l : ">").join("\n")) : "";
}
case "UL": case "OL": return list(el, ctx);
case "LI": return block("- " + children(el, ctx).trim()); /* a list item without its list */
case "TABLE": return table(el, ctx);
case "A": {
const text = children(el, ctx).replace(/\s+/g, " ").trim();
const raw = el.getAttribute("href") || "";
if (isBacklink(el) || /#/.test(raw) && /^[#¶§🔗\s]*$/.test(el.textContent)) return ""; /* anchors and "back to text" */
const href = abs(raw);
if (!href || /^#/.test(raw)) return text;
if (!text) return "";
const title = el.getAttribute("title");
return `[${text}](${href.replace(/\)/g, encodeURIComponent(")"))}${title ? ` "${title.replace(/"/g, "'")}"` : ""})`;
}
case "IMG": {
const src = imageSrc(el);
if (!src || /^data:/.test(src) && src.length > 2000) return "";
const alt = (el.getAttribute("alt") || "").replace(/[\[\]]/g, "").trim();
return `/g, encodeURIComponent(")"))})`;
}
case "PICTURE": {
const img = el.querySelector("img");
return img ? conv(img, ctx) : "";
}
case "FIGURE": {
const cap = el.querySelector("figcaption");
const body = [...el.childNodes].filter(n => n !== cap).map(n => conv(n, ctx)).join("").trim();
const caption = cap ? escText(cap.textContent.replace(/\s+/g, " ").trim()) : "";
return block(caption ? `${body}\n*${caption}*` : body);
}
case "VIDEO": case "AUDIO": {
const src = abs(el.getAttribute("src") || (el.querySelector("source") || { getAttribute: () => "" }).getAttribute("src"));
return src ? block(`[${tag === "VIDEO" ? "Video" : "Audio"}](${src})`) : "";
}
case "DL": {
const out = [];
for (const item of el.children) {
const text = children(item, ctx).replace(/\s+/g, " ").trim();
if (!text) continue;
out.push(item.tagName === "DT" ? `**${text}**` : `: ${text}`);
}
return block(out.join("\n"));
}
case "DETAILS": {
const sum = el.querySelector("summary");
const rest = [...el.childNodes].filter(n => n !== sum).map(n => conv(n, ctx)).join("");
return (sum ? block(`**${children(sum, ctx).trim()}**`) : "") + rest;
}
case "SUP": case "SUB": case "SPAN": case "SMALL": case "ABBR": case "TIME": case "LABEL": case "U": case "Q":
return children(el, ctx);
default: {
const inner = children(el, ctx);
const display = el.isConnected ? getComputedStyle(el).display : "";
return /^(inline|contents)/.test(display) ? inner : block(inner);
}
}
};
/* Tidy the result: no runs of blank lines, no trailing spaces, code untouched. */
const tidy = md => {
const out = [];
let inFence = null;
for (const line of md.split("\n")) {
const f = line.match(/^\s*(`{3,})/);
if (f && (!inFence || f[1].length >= inFence.length)) inFence = inFence ? null : f[1];
out.push(inFence || f ? line : line.replace(/[ \t]+$/, "").replace(/^ +(?![-\d>*]|\s)/, ""));
}
return out.join("\n").replace(/\n{3,}/g, "\n\n").replace(/(\\\n)\s*\n/g, "\n\n").trim() + "\n";
};
const meta = name => {
const el = document.querySelector(`meta[property="${name}"], meta[name="${name}"]`);
return el ? el.getAttribute("content").trim() : "";
};
const canonical = (document.querySelector("link[rel=canonical]") || {}).href;
const info = {
title: (meta("og:title") || document.title || "Untitled").trim(),
source: canonical || location.href,
author: meta("author") || meta("article:author"),
published: (meta("article:published_time") ||
(document.querySelector("time[datetime]") || { getAttribute: () => "" }).getAttribute("datetime") || "").slice(0, 10),
saved: new Date().toISOString().slice(0, 10)
};
let body;
if (fromSelection) {
/* A selection inside a table, list or code block loses its container when
cloned, so rebuild the missing parents around it. */
const holder = document.createElement("div");
for (let i = 0; i < selection.rangeCount; i++) {
const range = selection.getRangeAt(i);
let part = range.cloneContents();
let el = range.commonAncestorContainer;
if (el.nodeType !== 1) el = el.parentElement;
if (el && el.closest("table, ul, ol, pre")) {
while (el) {
const shell = el.cloneNode(false);
shell.appendChild(part);
part = shell;
if (/^(TABLE|UL|OL|PRE)$/.test(el.tagName)) break;
el = el.parentElement;
}
}
holder.appendChild(part);
}
body = tidy(conv(holder));
} else {
const root = findRoot();
body = tidy(conv(root));
if (!/^# /m.test(body)) body = `# ${info.title}\n\n${body}`;
}
const yaml = v => /[:#"'\[\]{}]|^\s|\s$/.test(v) ? `"${v.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"` : v;
const frontMatter = () => ["---",
...Object.entries(info).filter(([, v]) => v).map(([k, v]) => `${k}: ${yaml(v)}`),
"---", ""].join("\n");
/* Interface in a shadow root, so the page's CSS can't reach it. */
const host = document.createElement("div");
host.id = ID;
Object.assign(host.style, { position: "fixed", inset: "0", zIndex: "2147483647" });
const root = host.attachShadow({ mode: "open" });
const css = `
:host { all: initial; }
* { box-sizing: border-box; }
.shade { position: fixed; inset: 0; background: rgba(15,17,20,.45); }
.panel { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%);
width: min(860px, calc(100vw - 32px)); height: min(80vh, 760px); display: flex; flex-direction: column;
border-radius: 12px; border: 1px solid #dee2e6; background: #fff; color: #212529;
font: 13px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; box-shadow: 0 20px 50px rgba(0,0,0,.25); }
@media (prefers-color-scheme: dark) { .panel { background: #1b1e22; color: #e9ecef; border-color: #343a40; } }
.head { display: flex; align-items: center; gap: 10px; padding: 12px 16px; border-bottom: 1px solid rgba(128,128,128,.25); }
.title { font-weight: 700; font-size: 14px; }
.hint { opacity: .65; font-size: 12px; flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
textarea { flex: 1; width: 100%; resize: none; border: 0; outline: 0; padding: 14px 16px; background: transparent; color: inherit;
font: 12.5px/1.55 ui-monospace, Menlo, Consolas, monospace; tab-size: 4; }
.foot { display: flex; align-items: center; gap: 8px; padding: 10px 16px; border-top: 1px solid rgba(128,128,128,.25); }
.grow { flex: 1; }
button { font: inherit; font-size: 12px; padding: 5px 12px; border-radius: 6px; border: 1px solid #ced4da;
background: transparent; color: inherit; cursor: pointer; }
button:hover { border-color: #4dabf7; }
button.primary { background: #1c7ed6; border-color: #1c7ed6; color: #fff; }
.by { font-size: 11px; opacity: .55; margin-left: 8px; }
.by a { color: inherit; }
label { display: flex; align-items: center; gap: 6px; font-size: 12px; cursor: pointer; }
`;
try {
const sheet = new CSSStyleSheet();
sheet.replaceSync(css); /* works on pages whose CSP blocks inline <style> */
root.adoptedStyleSheets = [sheet];
} catch (e) {
const st = document.createElement("style");
st.textContent = css;
root.appendChild(st);
}
const words = body.replace(/```[\s\S]*?```/g, "").split(/\s+/).filter(Boolean).length;
root.innerHTML += `
<div class="shade"></div>
<div class="panel" role="dialog" aria-label="Page to Markdown">
<div class="head">
<span class="title">Page to Markdown</span>
<span class="hint"></span>
<button data-x>Close</button>
</div>
<textarea spellcheck="false"></textarea>
<div class="foot">
<label><input type="checkbox" data-fm checked> Front matter</label>
<span class="by">by <a href="https://pablomurad.com" target="_blank" rel="noopener">Pablo Murad</a></span>
<span class="grow"></span>
<button data-dl>Download .md</button>
<button class="primary" data-copy>Copy</button>
</div>
</div>`;
const $ = s => root.querySelector(s);
const area = $("textarea");
$(".hint").textContent = `${fromSelection ? "Selection" : "Page"} · ${words.toLocaleString()} words · ${Math.max(1, Math.round(words / 230))} min read`;
const render = () => { area.value = ($("[data-fm]").checked ? frontMatter() + "\n" : "") + body; };
render();
document.documentElement.appendChild(host);
area.focus();
area.setSelectionRange(0, 0);
area.scrollTop = 0;
const flash = (btn, text) => {
const was = btn.textContent;
btn.textContent = text;
setTimeout(() => { btn.textContent = was; }, 1400);
};
const copy = btn => {
const done = () => flash(btn, "Copied");
const fallback = () => {
area.select();
try { document.execCommand("copy") ? done() : flash(btn, "Press Ctrl+C"); }
catch (e) { flash(btn, "Press Ctrl+C"); }
};
if (navigator.clipboard && window.isSecureContext) navigator.clipboard.writeText(area.value).then(done, fallback);
else fallback();
};
const download = () => {
const slug = info.title.toLowerCase().normalize("NFKD").replace(/\p{M}/gu, "")
.replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 80) || "page";
const url = URL.createObjectURL(new Blob([area.value], { type: "text/markdown;charset=utf-8" }));
const a = document.createElement("a");
a.href = url;
a.download = slug + ".md";
root.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 2000);
};
/* Keep the page's own shortcuts from firing while the panel is open. */
const onKey = e => {
if (e.key === "Escape") { e.preventDefault(); close(); return; }
if (e.composedPath().includes(host)) e.stopPropagation();
};
const close = () => {
document.removeEventListener("keydown", onKey, true);
host.remove();
};
host.__close = close;
root.addEventListener("click", e => {
const t = e.target;
if (t.closest("[data-x]") || t.classList.contains("shade")) close();
else if (t.closest("[data-copy]")) copy(t.closest("[data-copy]"));
else if (t.closest("[data-dl]")) download();
});
$("[data-fm]").addEventListener("change", render);
document.addEventListener("keydown", onKey, true);
})();curl -O https://pablomurad.com/snippets/page-to-markdown.js

On the MuradKey post it came out at 2,392 words, with its five margin notes turned into footnotes at the end of the file.
Notes
-
Services that convert a page from its address download it on their own servers, so they get the logged-out version of the page, if they can reach it at all. ↩
-
It scores the page's containers by how much paragraph text they hold and keeps the one with the article. Reader modes in browsers work on a more elaborate version of the same idea. ↩
-
Footnotes weren't part of the original Markdown. The
[^1]syntax came from PHP Markdown Extra, and most Markdown tools read it today. ↩ -
Front matter is the block between two
---lines at the top of the file. Jekyll made it popular, and static site generators and note apps like Obsidian read it as the note's metadata. ↩