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?
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);
};
}]);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With