Escape HTML Using JavaScript

August 1st, 2008

I’m fooling around with a chat application and the first time Steve tried it out, he sent through the following as a message.

<script>alert('hi');</script>

Obviously, I got an alert and laughed because I forgot to escape html in the chat body. Then, of course, before I could fix it, he sent through this:

<script>document.getElementsByTagName('body')[0].style.display = 'none';</script>

Quite promptly, my whole screen went blank. Escaping the output in the templating engine I was using was simple, but what about when inserting a new chat using JavaScript? In Prototype, the following works.

$('foo').update("<script>alert('hi');</script>".escapeHTML());

I was using jQuery, though, so I searched around a bit for something that does the same. I’m usually quite deft with Google but I couldn’t find anything. The following is what I ended up with.

$('#foo').append(document.createTextNode("<script>alert('hi');</script>");

Since I couldn’t find it anywhere, I thought I would put it here. Hopefully, it won’t take the next bloke a few hours to figure it out.

2 Responses to “Escape HTML Using JavaScript”

  1. I’ve got a little chat app working, and I went about this slightly differently. I do a little page.insert_html in the create action, which calls up a partial that formats the message with a helper before putting it back on the screen.

    This chat app has a little problem with slow connections that I’ll need to sort out, but I know the cause and have an idea about how to solve it. In any case, I’d be interested to see what you come up with if it’s open-source. If you’re curious about my implementation, you can start digging into it here:

    http://github.com/trevorturk/el-dorado/tree/master/app/controllers/messages_controller.rb

  2. @Trevor – Well right now it’s in python running on Google’s App Engine, though closed down until it’s ready. I’m thinking I might open source it but not sure yet. I’m just polling every three seconds and returning json. I keep track of the last seen message and just keep polling for any messages greater than that.

About This Site

Addicted to New is the personal website of John Nunemaker (Noo-neh-maker), a Web Developer enamored of Ruby on Rails and a wide-eyed fan of all things new and cool.