Reputation: 1967
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' lo')">Hello</a>
Why doesn't the below work and how can I make it work?
Upvotes: 1
Views: 40
Reputation: 163301
You're inserting a character reference for a single quote '
.
Even though you're using '
, when it hits JavaScript, it's a quote mark. Therefore, you're ending the string literal and causing a syntax error.
Upvotes: 2
Reputation: 943217
'
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 '
safely) and then read the attribute from your JavaScript.
Upvotes: 3