10

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?

Ian Hunter
  • 9,466
  • 12
  • 61
  • 77
  • Copy the source of the directive and make your own from it ;) – Guillaume86 Jun 06 '13 at 18:18
  • I could (and sadly I've had to do it with angular-resource), but I want to avoid diverging from the base files as much as possible. – Ian Hunter Jun 06 '13 at 18:22
  • Did you end up with a solution to this? or did you create your own? – heisa May 08 '15 at 08:10
  • @user3319803 I ended up forking Angular's and modifying it to our needs: https://github.com/BYU-ODH/hummedia-client/blob/master/app/js/custom-sanitize.js though I hadn't checked jdforsythe's solution as this was already done by the time that solution was offered, so theirs might be a better route – Ian Hunter May 08 '15 at 18:05

2 Answers2

5

You can decorate the $sanitize service to avoid changing the source files. Here's an example that just logs what happens inside $sanitize. You can do what you need to filter unwanted elements.

var app = angular.module("app", ["ngSanitize"]);

app.config(function($provide){
    $provide.decorator("$sanitize", function($delegate, $log){
        return function(text, target){

            var result = $delegate(text, target);
            $log.info("$sanitize input: " + text);
            $log.info("$sanitize output: " + result);

            return result;
        };
    });
});

Note that inside of the decorator, $delegate refers to the $santize. You'll filter what you want out of the input before calling $delegate(text, target) then return the result.

jdforsythe
  • 1,057
  • 12
  • 22
5

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);
            };
    }]);
vloginov
  • 92
  • 1
  • 4