strip-dom-tags
v0.1.1
Published
Safely strip DOM tags from a HTML string to prevent XSS attacks.
Readme
strip-dom-tags
Safely strip all DOM tags from a string to prevent XSS attacks
This module exposes a single functions, that strips a HTML string from tags. It uses the browser DOMParser API (https://caniuse.com/#search=domparser) internally to do the parsing and stripping. It has no dependencies.
You can whitelist different tags and attributes that are allowed, but javascript: attribute values will always be stripped.
This module only works in the browser, it will always return the empty string if invoked server-side.
Usage
stripTags(html : string, whitelistedTags = [] : string[], whitelistedAttributes = [] : string[], visitNode?: (node: Node) : Node) : stringhtml- The string to strip from HTML tags.whitelistedTags- A list of HTML tags that are allowed, likeaandimg. This is case-insensitive. The default is no tags are allowed.whitelistedAttributes- A list of HTML attributes that are allwed, likehrefandsrc. The passed attributes will be allowed on any tag that is whitelisted. So it is possible for aatag to get asrcattribute. Note that attribute values starting withjavascript:or containing\nwill always be stripped.visitNode- A function that will be invoked on every resulting DOM node after it has been stripped. You can use this to remove invalid attribute, or addtargetattribute toatags for example. You can also return a different node (maybe replaceimgwithpicture).
Return value
The function returns a HTML string, that is stripped of all the listed tags.
