How to Convert Page Source Code & HTML to Markdown Cleanly
Published: August 19, 2026 ยท By Michael Vereb
Key Takeaways
- Raw page source code and HTML introduce massive token overhead and noise into LLM prompts.
- Markdown parsers support inline HTML and do not act as Cross-Site Scripting (XSS) boundaries.
- Robust extraction requires DOMPurify sanitization combined with Mozilla Readability content heuristics.
- Turndown.js converts sanitized DOM elements into clean CommonMark syntax with preserved code blocks.
- Zero-server client-side tools protect data privacy by processing all code locally in the browser.
The Hidden Token Cost of Raw Web Markup
Feeding raw webpage source code into Large Language Models (LLMs) is one of the most common mistakes in modern AI context engineering. When you copy raw HTML directly from DevTools or scrape a document using standard HTTP GET requests, you inherit thousands of lines of non-semantic overhead. Navigation menus, SVG icons, advertising tracking scripts, iframe embeds, and nested container divs bloat your prompt without adding semantic value.
In a production retrieval pipeline, this markup waste directly penalizes your application. Raw HTML consumes up to 75% of your available context window, inflates inference token costs, and forces the model's attention mechanism to filter syntax noise instead of reasoning over core facts.
Converting web source to clean, standardized Markdown isolates the authoritative content while stripping the visual presentation layer. However, executing this conversion reliably requires understanding DOM tree extraction, client-side security boundaries, and AST transformation engines.
Client-Side DOM Parsing and Execution Security
In a zero-server web architecture, converting HTML to Markdown begins inside the browser using native JavaScript APIs. The standard interface for turning raw markup strings into a navigable document object is the MDN Web Docs: DOMParser interface.
Calling new DOMParser().parseFromString(htmlString, "text/html") creates an isolated in-memory Document. Unlike setting innerHTML directly on an active element, an in-memory document created by DOMParser is inert: scripts do not execute immediately, and external resources are not fetched automatically.
However, treating an in-memory DOM as safe is a critical vulnerability. If parsed nodes are ever attached to the active document or re-rendered as unescaped HTML, any embedded event handlers or malicious attributes will execute immediately.
Why Markdown Parsers Are Not XSS Boundaries
A widespread misconception among frontend developers is that converting HTML into Markdown inherently sanitizes malicious input. It does not. The CommonMark and GitHub Flavored Markdown specifications explicitly support raw HTML passthrough by design.
If source markup contains obfuscated script tags, inline onload event listeners, or dangerous javascript: protocol URIs in hyperlink hrefs, a naive Markdown converter will preserve them verbatim. When that Markdown is subsequently rendered back to HTML in a web dashboard, documentation viewer, or chat interface, it triggers DOM-based Cross-Site Scripting (XSS).
To prevent exploitation, you must enforce a strict sanitization pass before passing nodes to a Markdown conversion ruleset. Regular expressions are fundamentally incapable of validating nested or malformed HTML structures. The industry standard solution is Cure53 / DOMPurify, a security-hardened sanitizer that traverses the in-memory DOM tree recursively, validating every element and attribute against strict allowlists while neutralizing mutation-based XSS vectors.
Heuristic Content Isolation with Readability
Once source HTML is sanitized, the next challenge is isolating the primary article body from surrounding page boilerplate. Modern web pages are cluttered with sticky navigation headers, social sharing widgets, related post sidebars, and cookie consent banners.
Rather than writing custom CSS selectors for every target website, production workflows leverage Mozilla Readability, the standalone heuristic engine that powers Firefox Reader View. Readability evaluates DOM nodes based on paragraph text density, link-to-text ratios, and class/ID naming patterns (such as article, entry-content, vs nav, sidebar, comment).
Elements scoring below dynamic thresholds are pruned from the tree, leaving only the primary semantic narrative, code samples, and data tables.
Transforming Clean DOM Trees to Markdown with Turndown
With the cleaned content tree isolated, the final step is mapping HTML elements into standard Markdown syntax. The premier open-source library for AST-driven conversion is Mixmark-io / Turndown.
Turndown walks the DOM tree and executes modular rules for each tag type:
- Headings (
h1throughh6) map directly to hash prefixes (#to######). - Emphasis tags (
strong,em) map to asterisks and underscores. - Unordered and ordered list items convert to indented dashes and numbers.
- Code blocks (
pre > code) preserve language info strings and whitespace formatting. - Anchor tags map to standard Markdown links
[text](url)with validated URLs.
You can test this entire pipeline in real-time without sending any data to a remote server by using the free interactive HTML to Markdown Sandbox.
One-Click Extraction with the Copy Markdown Extension
For web scraping, research, and prompt preparation, automating this pipeline inside your browser eliminates repetitive DevTools inspect-and-copy loops. The Copy Markdown Chrome Extension executes on-page DOM sanitization, readability filtering, and Markdown generation natively with a single keyboard shortcut or click.
Because processing runs 100% locally in your browser, your proprietary documentation, private intranet dashboards, and sensitive code snippets never touch a third-party server.
Summary
Converting page source code to clean Markdown eliminates up to 75% of token bloat when feeding web content to AI context windows. A secure extraction pipeline combines in-memory DOM parsing, DOMPurify tree sanitization, Mozilla Readability content isolation, and Turndown AST conversion. By running these operations entirely in the browser, you achieve maximum token efficiency while preserving data privacy.
Ready to streamline your AI workflow? Install the Copy Markdown Chrome Extension or try the browser-based HTML to Markdown Sandbox today.
Frequently Asked Questions
Why not just copy raw HTML directly into ChatGPT or Claude?
Raw HTML contains thousands of characters of non-semantic code, including script tags, styling classes, and layout wrappers. This consumes massive amounts of prompt tokens, increases API costs, and distracts the LLM's attention mechanism from the core textual content.
Does converting HTML to Markdown automatically remove malicious scripts?
No. Markdown specifications allow raw HTML passthrough. If malicious tags or JavaScript event handlers exist in the source HTML, they will persist in the Markdown output. You must sanitize the DOM using tools like DOMPurify prior to conversion.
How does Readability determine what is the main article content?
Mozilla Readability scores DOM elements by analyzing text length, paragraph density, link density, and semantic class names. Sections with high link counts or boilerplate classes (like sidebars and footers) are penalized and stripped away.
Get the Copy Markdown Extension
Extract clean Markdown, CSS design tokens, and links from any webpage with 1 click or keyboard shortcut.