3

I'd like to make a simple chat, and, at the beginning, just parse ':)' and add an image before appending the message. Here's what I tried :

var string = "The message the user wrote";
var message = $('<div class=\"chat-message\"></div>').text(string);            
message.html(message.text().replace(':)', '<img src="smile.png"/>')).appendTo('#chat-messages');

Okey, it's works, but let's imagine someone sends this :

<img src="Some illicite picture"/>

Well, it would just display the picture, and I don't want the users to inject HTML code in the page.

So, how can I do ?

Albzi
  • 15,431
  • 6
  • 46
  • 63
Maxence Henneron
  • 495
  • 1
  • 4
  • 10
  • 1
    What about enclosing all chat content with `
    ` or `` blocks unless explicitly matched and replaced with HTML by you?
    – zero298 Mar 18 '14 at 16:58
  • 1
    wont `message.text()` strip that out? – Adween Mar 18 '14 at 17:02
  • Actually, since you are already using jQuery, consider @Adween suggestion of using `message.text()`. It is similar to calling `document.createTextNode()` which is a native way of doing escaping. Consider this article: [**HTML escaping in Javascript**](http://shebang.brandonmintern.com/foolproof-html-escaping-in-javascript/) – zero298 Mar 18 '14 at 17:08
  • @zero298 it is already calling `text()` Here: `message.text().replace(':)', '')` this will strip all html and just get the text, then replace the smiley `:)` with the html for the image – Adween Mar 18 '14 at 17:10
  • Well I tried the text() alternative, but using message.html() replace the escaped text with html.. I just want the to be interpreted as HTML and only keep the message escaped – Maxence Henneron Mar 18 '14 at 17:37

1 Answers1

2

You should escape the HTML chars at Serverside, because Javascript could be bypassed. In PHP this is done by the htmlspecialchars function, so: $newText = htmlspecialchars($oldtext);

Hoff
  • 243
  • 1
  • 6
  • Well, I coded the server myself in C++, it's a websocket server, I made my own implementation. So.. the client is in pure HTML/JS – Maxence Henneron Mar 18 '14 at 19:31
  • Well then escape it with C++(replace < and > by < > should do it) and replace the smilies on clientside with js. – Hoff Mar 19 '14 at 14:09