Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape user-generated chat messages but render links

User enter chat messages, which gets rendered directly to the page using Mustache templates. Obviously, HTML should be escaped to prevent HTML injection, but then again links should be rendered as <a href='...'>.

There are different approaches I've tried to use {{{ ... }}} to return the unescaped HTML content, which means the link would get rendered and I need to take care of HTML escaping myself. Is there a safe way of doing that without relying on a half-baked solution I write myself?

jQuery.text() would be great, but I guess it will render the <a> again as text.

What else can I do here?

like image 361
Mahoni Avatar asked Aug 05 '15 10:08

Mahoni


1 Answers

If you don't want to write your own escaping or parsing solution there is a jQuery plugin to handle links called Linkify. You could simply escape messages and then parse them client-side.

Example of how it works:

var text = "<div>Test<br>Test<br>Test http://stackoverflow.com</div>";
$('div').text(text);

// Before: &lt;div&gt;Test&lt;br&gt;Test&lt;br&gt;Test http://stackoverflow.com&lt;/div&gt;

$('div').linkify();

// After: lt;div&gt;Test&lt;br&gt;Test&lt;br&gt;Test <a href="http://stackoverflow.com" class="linkified" target="_blank">http://stackoverflow.com</a>&lt;/div&gt;
like image 52
JacobMiki Avatar answered Nov 06 '22 05:11

JacobMiki