1

I've got a js-function which takes string as a parameter and get it displayed in a div element. Such string may contain html tags.

How do I force JS display inner text in div-elements as html-text with html-tags. And, also, what is an adequate way to filter particular tags, i.e. apply certain tags for styling and just print others.

Sergey
  • 1,168
  • 2
  • 13
  • 28
  • I fear this question will once again awaken zalgo. http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – cillierscharl Mar 19 '12 at 09:13

2 Answers2

4

You just need to replace & and < (and optionally > if you like, but you don't have to) with their respective entities, using String#replace (spec, MDC) for instance.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thank's a lot. Yeah, I just encode "<" with its code except those "<" which follow cetain tags. I think that in my case it is sufficient to avoid any XSS attacks. – Sergey Mar 19 '12 at 10:41
  • 1
    @user1041195 do not forget that **any** tag can have embedded even handler with JavaScript and "javascript:" is a valid prefix for URLs. If your users may insert HTML do not handmade this. – Adriano Repetti Mar 19 '12 at 10:59
  • 1
    @user1041195: Seconding what Adriano said: If you're going to allow some HTML tags, your best bet is to use an XSS library rather than doing this yourself. If you do it yourself, do a whitelist of tags (disallowing anything else) and for each tag, a whitelist of the attributes you allow on that tag and (in some cases) the form those attributes are allowed to take. You wouldn't want to allow `Look, bunnies!` or similar. – T.J. Crowder Mar 19 '12 at 11:03
  • Yes, attributes are also to be considered. Adriano, T.J. Crowder, thanks. – Sergey Mar 19 '12 at 11:45
  • @T.J.Crowder Yes, I think it's too easy to forget something about HTML (specially if this is his _first_ time) but you've got my +1 for the straightforward explanation of what he should do! – Adriano Repetti Mar 19 '12 at 11:56
1

And, also, what is an adequate way to filter particular tags, i.e. apply certain tags for styling and just print others.

To put directly user inserted HTML code is dangerous for XSS. You should use some tool to sanitize HTML code (here on StackOverflow, for example, you can use some HTML tags).

As posted in this question here on SO you can use this client-side sanitizer: http://code.google.com/p/google-caja/source/browse/trunk/src/com/google/caja/plugin/html-sanitizer.js On the other hand you may need to do this on the server-side, which one depends on your environment (ASP.NET? PHP?).

Community
  • 1
  • 1
Adriano Repetti
  • 65,416
  • 20
  • 137
  • 208