src/purifier/README.md
The AMP Purifier library contains an AMP-specific configuration for DOMPurify.
This library is internally used by amp-mustache
to sanitize rendered Mustache.js templates before displaying them.
import {Purifier} from '#purifier';
const purifier = new Purifier(document);
purifier.purifyHtml('a<script>b</script>c'); // "ac"
import Mustache from 'mustache';
import {Purifier} from '#purifier';
const purifier = new Purifier(document);
const _unescapedValue = Mustache.Writer.prototype.unescapedValue;
Mustache.Writer.prototype.unescapedValue = function (token, context) {
const result = _unescapedValue(token, context);
return purifier.purifyTagsForTripleMustache(result);
};
const html = Mustache.render(template, data);
const body = purifier.purifyHtml(html);
for (const child of body.children) {
targetElement.appendChild(child);
}
The library has only a single export, the Purifier class.
Purifier constructornew Purifier(doc, config, attrRewrite)
docThe base document to use. Usually window.document.
configOptional
DOMPurify configuration to use in addition to the AMP default one.
attrRewriteOptional
A function that, if provided, will be called for every sanitized attribute in the output to change its value. It accepts the following attributes:
tagName - name of tag containing the attributeattrName - name of attributeattrValue - current attribute valueThe returned value of this function is used as the new attribute value.
For example, this replaces the href of all <a> elements with example.com:
new Purifier(window.document, {}, (tagName, attrName, attrValue) => {
if (tagName === 'a' && attrName === 'href') {
return 'https://google.com';
}
return attrValue;
});
purifyHtmlpurifyHtml(html)
Uses DOMPurify to sanitize HTML in a way that ensures the fragment is valid AMP.
htmlThe HTML code to sanitize (purify).
A <body> element containing the sanitized html markup.
purifyTagsForTripleMustachepurifyTagsForTripleMustache(html)
Uses DOMPurify to sanitize HTML with stricter policy for unescaped templates
e.g. triple mustache. See amp-mustache documentation
for more information.
htmlThe HTML code to sanitize (purify).
Sanitized HTML (as a string).
getAllowedTagsgetAllowedTags()
Gets a copy of the map of allowed tag names (standard DOMPurify config).
An object containing the list of allowed tags according to AMP's DOMPurify config.
validateAttributeChangeReturns whether an attribute addition/modification/removal is valid according to AMP's DOMPurify config.
validateAttributeChange(node, attr, value)
nodeDOM node to check.
attrAttribute name.
valueAttribute value (can be null).
true if the given attribute change is valid, false otherwise.