Using ngSanitize to allow some html tags

2.3k views Asked by At

I have an insecure string from the user that I want to display.

  • I want a few html-tags like < strong > (without spaces) to work.
  • All other html should be displayed like it was typed in (that is < should be replace with & lt; and so on)

I'm pretty sure I can use ngSanitize to do this but I can't figure out how.

2

There are 2 answers

1
Chad Robinson On BEST ANSWER

$compileProvider allows you to set up sanitization "whitelists" for HREF and SRC URLs:

app.config(function($compileProvider) {
    var imgSrcSanitizationWhitelist = /^\s*(https?|ftp|file):|data:image\//;
    $compileProvider.imgSrcSanitizationWhitelist(imgSrcSanitizationWhitelist);
});

However, the whitelists for "safe" tags are hard-coded and can't be changed the same way. You can see the list here in the source:

https://github.com/angular/angular.js/blob/master/src/ngSanitize/sanitize.js#L186

There is an open request to enhance this functionality:

https://github.com/angular/angular.js/issues/5900

But it has not been completed (yet).

In the meantime, you have a few options:

  1. "Fork" the project and adjust ngSanitize to suit your purposes. Most people don't like to "hack core" in this way, but it's the whole point of Open Source to be able to do things like this. This module doesn't change so much that it would be that hard to keep it relatively up to date as you develop your project.
  2. Live with the list defined there. Most of the time you find that this list is actually pretty good, and it's just that IMG or A HREF tags are broken. That's not because the tag is filtered - that's because THOSE are white-listed separately, and you can use the technique above to accept specific URLs into each of those tags as "safe".
0
Colin Claverie On