Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$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?

like image 471
Ian Hunter Avatar asked Jun 06 '13 18:06

Ian Hunter


2 Answers

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);
            };
    }]);
like image 129
vloginov Avatar answered Oct 05 '22 21:10

vloginov


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.

like image 20
jdforsythe Avatar answered Oct 05 '22 21:10

jdforsythe