user1985273
user1985273

Reputation: 1967

Using user input inside JavaScript breaks code

I am using user input inside JavaScript. And of course to be safe my framework is changing some symbols to HTML codes. But for some reason that breaks my JavaScript. So for example this works:

<a onclick="alert('hello')">Hello</a>

But this doesn't:

<a onclick="alert('hel l&#039; lo')">Hello</a>

Why doesn't the below work and how can I make it work?

Upvotes: 1

Views: 40

Answers (2)

Brad
Brad

Reputation: 163301

You're inserting a character reference for a single quote '.

Even though you're using &#039;, when it hits JavaScript, it's a quote mark. Therefore, you're ending the string literal and causing a syntax error.

Upvotes: 2

Quentin
Quentin

Reputation: 943217

&#039; is HTML for '. The HTML is parsed and the result passed to the JavaScript compiler so your JavaScript is alert('hel ' lo') and you can't have an unescaped ' in a string literal delimited with ' characters.

Escaping data to make it safe to insert into HTML is not enough to make it safe to insert into JavaScript which is then inserted into HTML in turn.


Store the user input in a data-* attribute (which is plain HTML so you can use &#039; safely) and then read the attribute from your JavaScript.

Upvotes: 3

Related Questions