-
Notifications
You must be signed in to change notification settings - Fork 446
Safe Mode
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>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><a href="javascript:alert()">Click me</a></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