Live Markdown Preview with Marked and DOMPurify: Experience HTML Sanitization

プログラミング・Web開発カテゴリを表すパンダのイラスト Programming / Web Development

About this article
This article is generated through an automated generation workflow utilizing generative AI. Using dummy data and browser operations, we will learn the use cases, mechanisms, and observation points during failures of Marked and DOMPurify. No access to real services or personal information is performed.

Verification Status:Verified official documentation and HTML/JavaScript of GitHub pinned commits on 2026-10-30. Actual browser operations, CDN fetching, and rendering/audio output were not executed, and the results in the text are expected values from the code.

ItemContent
TargetModern browsers such as Chrome, Edge, and Firefox (actual device compatibility unverified)
Libraries UsedMarked and DOMPurify (tutorial versions: Marked 16.3.0 / DOMPurify 3.4.17)
CostNo paid API is required for the demo source itself. Communication fees and usage conditions depend on the environment.
DataDummy data within the page. No authentication info, location data, or enterprise data required.
Learning ActionDisplay a sanitized HTML preview when Markdown is entered

Why try this technology?

When writing a blog, being able to preview Markdown makes it easier to check the formatting of headings and bullet points. However, the process of generating HTML from Markdown does not automatically mean that safe HTML is produced. Marked plays the role of parsing Markdown into HTML, while DOMPurify removes dangerous elements and attributes from HTML. Combining both allows you to learn the boundary between convenience and security through a small demo. This does not replace authentication or storage functions in actual public CMSs.

When building a working sample, rather than stopping at the mere fact that the visual element moved, you need to distinguish which input altered which variable and which process updated the rendering. In this learning material, we will make those changes explicit on the screen. When integrating this into an actual service, design the authentication and data persistence processes separately.

Try it first: Live demo and expected results

First, display the heading, bold text, and italicized text of 'Starry Sky Notes' in Markdown, then click the update button. Verify whether the heading and bullet points are reflected as an HTML structure. Next, rewrite the text to a fictitious string and observe whether the preview changes. When observing the behavior, consider the string before Markdown conversion separately from the result reflected in the DOM. 'SUCCESS' at the bottom of the screen simply means the process completed without exceptions and is not a guarantee of security against all attacks.

Prerequisites to check before operation

  1. Confirm that your PC can execute JavaScript. Administrator privileges are not required.

  2. Open the browser developer tools and prepare to check the Console for errors and the Network tab for CDN retrieval failures.

  3. If the demo is not actually published, save the Daily Codeindex.htmlandapp.jsin the same folder and open them using a local HTTP server. When using modules, direct execution via file:// is not guaranteed to work.

  4. Compare the results before and after the operation. If they differ from the expected values, record what failed to display first.

Overview of the mechanism

flowchart LR
    A["入力やクリック"] --> B["イベントを受ける"]
    B --> C["MarkedとDOMPurify のAPI"]
    C --> D["状態と描画を更新"]
    D --> E["見た目と文字で確認"]

This diagram is a conceptual illustration for learning purposes and does not represent internal browser implementations or the details of network communication. Regardless of the library used, tracing 'which variable the operation reaches' remains consistent.

Local verification when the public demo is unavailable

From the pinned commit, download theHTML bodyandJavaScript bodyvia the GitHub Raw view respectivelyindex.htmlandapp.jsas and save them in the same new folder. The README alone will not work. On Windows, open PowerShell in that folder,py -3 -m http.server 8000 --bind 127.0.0.1and on Linux/macOS, runpython3 -m http.server 8000 --bind 127.0.0.1, then openhttp://127.0.0.1:8000/on the same PC. To exit, runCtrl+Cin the terminal. Because the browser fetches the library itself from an external CDN, if a connection cannot be established, check the Console and Network errors. This procedure is a reproduction guide and not an actual browser measurement report for this article.

How it works: Deciphering the API

Marked's parse generates an HTML string from Markdown text. Because Markdown itself can contain HTML, event attributes such as onerror may sometimes be mixed into the parsed result. Marked does not sanitize this HTML. Before passing the generated result to innerHTML in the browser, DOMPurify.sanitize restricts it to safe elements. In this demo, images, iframes, styles, and scripts are further disabled, and external links are made unclickable. This is a restriction intended for educational purposes, and permitted elements must be explicitly designed according to the use case.

How to read the minimal code

// Marked単体のHTMLをinnerHTMLへ直渡ししない
const unsafeHtml = marked.parse(markdownText);
const safeHtml = DOMPurify.sanitize(unsafeHtml);
preview.innerHTML = safeHtml;

The above is an excerpt highlighting the key points of the API. It is not a complete, standalone file that can be copied and executed.Please check the README and demo files on the Daily Code sidefor the complete set of HTML and implementation required to run it. Trace which functions select HTML elements and which lines update numerical values, and test them with known fictitious values.

Changing only one condition and comparing

Adding regular bold text to the input converts it into a strong element. On the other hand, even if you input Markdown containing images, the demo does not display the images. This is because loading external images was intentionally disabled. When integrating into a public CMS, allow only necessary tags and verify URL protocols and link attributes as well. It is important to be able to modify Markdown syntax and HTML permission rules independently.

The procedure for comparison is to record the initial value, change only one place, and check whether the result appears in the expected location. If you change multiple inputs at once, it becomes impossible to tell what caused the effect. Verify all the way through the operation of reverting to the pre-change state.

Where to look when something fails

It is a mistake to judge something as "secure" just because it has passed through a Markdown conversion library. If you concatenate unsafe HTML again after processing the HTML string, the meaning of sanitization is lost. In practical operations, updates to HTML Sanitizers, CSP, and Trusted Types are also subject to consideration. When publishing user input as-is, appropriate validation is required not only on the browser side but also on the server side. This sample is a simple browser display experiment and does not substitute for security guarantees or penetration testing.

Observed statePoints to isolateExample response
The screen does not change from the initial stateScript acquisition, initialization, and event registrationCheck Console, Network, and script tags
The display changes, but the meaning is incorrectInput values, arrays, units, and update targetsFix the values and check condition by condition
The button cannot be clickedSelector and DOM generation orderCheck the HTML to see if the IDs match
Does not work on some devices onlyBrowser features, permissions, CDN, and performanceRecord the device and version, and the reproduction steps

In-browser errors and public web server failures are different. The former is investigated from developer tool error details, and the latter from HTTP responses and asset delivery conditions. Not describing an unknown failure as a success enhances the reliability of technical notes.

Application to Business and Learning

It can be applied to technical document previews, notepad applications, lightweight CMS, and internal Wiki prototyping. Actual editing permissions, revision history, publishing workflows, rollbacks, and prevention of malicious file uploads are separate business requirements. Simply choosing a preview library does not complete the security of the entire publishing infrastructure.

Decisions to Make Before Implementation

When publishing to readers, determine where the displayed data comes from, who can modify it, the types of information remaining on the screen, and the verification items when updating the library. This demo has neither login nor server persistence. Therefore, before adding operational features, we recommend first distinguishing between the minimum part that displays as expected and the part that requires operational reliability, permissions, and backups. Since third-party CDNs involve external communication, advance verification is required to ensure they are permitted on the corporate network.

Comparing with Alternative Methods

MethodSuitable ScenariosPoints to note
Marked and DOMPurifyScenarios suited for purposes such as displaying a sanitized HTML preview when Markdown is inputRequires updates of dependent libraries and management of usage terms
Standard browser APIsBuilding small features in-houseChecking specifications and compatibility on your own
Static images and tablesExplanations that do not require interactionCannot experience state changes on the spot

Libraries are tools to be chosen when needed. Compare what you want to achieve against the learning cost. Avoiding making "adding a library" the primary objective makes small pages easier to maintain.

GitHub Sample

The blog post focuses on background and concepts, while Daily Code provides code for execution and modification, separating their roles. APIs for posting and saving to external services are not included.

Official Information and Primary Sources

Checked Reference Scope:Refer to the official documentation as of the October 27, 2026 edit. This does not guarantee future changes to the linked destinations or all CDN asset responses.

Supplementary Information on Verification Scope

The fixed sources stored on GitHub were cross-checked with the official API descriptions. Browser operations, CDN loading, and results on individual operating systems have not been verified. During actual operation checks, inspect the Console and Network, and do not conclude that all conditions are successful based solely on the SUCCESS display on the screen.

Document information

Article title
Live Markdown Preview with Marked and DOMPurify: Experience HTML Sanitization
Published
Updated
Source
https://papanda925.com/?p=18301&lang=en

License: Text and original figures for which this site holds the relevant rights are available under CC BY 4.0 , unless otherwise noted. This article may include content created or edited with generative AI. If code has a separate license notice or a linked GitHub repository license, that license takes precedence for the code. Quotations, third-party materials, images, and trademarks are excluded from this license. Usage policy

Copied title and URL