Skip to content
Crozzers edited this page May 14, 2026 · 1 revision

The recommended approach for safely and comprehensively sanitising HTML is to use a 3rd party library.

There are a few options around:

Example:

import markdown2
import nh3

nh3.clean(markdown2.markdown('<a href="javascript:alert()">Click me</a>'))
# <p><a rel="noopener noreferrer">Click me</a></p>

Built-in safe mode

This library does include a very limited "safe mode". This has been a part of the library since 2007 and is maintained for now, but may be deprecated in the future if the maintenance burden becomes too high (see #703 for some discussion on this).

Example:

import markdown2

markdown2.markdown('<a href="javascript:alert()">Click me</a>', safe_mode='escape')
# <p>&lt;a href="javascript:alert()"&gt;Click me&lt;/a&gt;</p>
markdown2.markdown('<a href="javascript:alert()">Click me</a>', safe_mode='replace')
# <p>[HTML_REMOVED]Click me[HTML_REMOVED]</p>

Ultimately, this library's main focus is markdown conversion, not HTML sanitisation. And so whilst every effort is made to ensure safe mode is as safe as possible, it will never be developed or tested nearly as thoroughly as any 3rd party library. Use at your own risk

![alt](url)

Clone this wiki locally