Search code examples
javascriptangularjsangularjs-directivesanitization

$sanitize Custom Whitelist


The $sanitize service tells me that

All safe tokens (from a whitelist) are then serialized back to properly escaped html string.

I want to only display an even smaller subset of HTML (viz em,p,a, and strong). Is there a way to easily modify the $service whitelist without having to modify the core JavaScript?


Solution

  • You can use $delegate (as jdforsythe mentioned) and some other library. I personally use sanitizeHtml in my project because it allows me to choose which tags to allow. The setup:

    angular
        .module('myApp', [])
        .config(['$provide', ($provide) => {
            $provide.decorator('$sanitize', ['$delegate', ($delegate) => {
                return function(text, target) {
                    const preSanitizedText = sanitizeHtml(text, {
                        allowedTags: ['b', 'i', 'em', 'strong', 'a']
                    });
                    return $delegate(preSanitizedText, target);
                };
        }]);