Escaping single and double quotes in JavaScript onclick event handler

The simple code block below results in a javascript error if ${photoCaption} contains single or double quotes.

<a href="#" onclick="
		                 $('#photo_caption').text('${photoCaption}');
	                ">

So I thought that It needs to be Javascript escaped. I used escapeJavaScript method of org.apache.commons.lang.StringEscapeUtils class.
First I inserted the code below (escapeJavaScript function) to tags.tld. Short name for my tag lib is ch

<taglib>
	...
	<short-name>ch</short-name>
	...
	<function>
		<name>escapeJavaScript</name>
		<function-class>
			org.apache.commons.lang.StringEscapeUtils
		</function-class>
		<function-signature>
			java.lang.String escapeJavaScript(java.lang.String)
		</function-signature>
	</function>
	...
</taglib>

I used escapeJavaScript function below in onclick event handler.

<a href="#" onclick="
		                 $('#photo_caption').text('${ch:escapeJavaScript(viewPhotoCaption)}');
	                ">

It escaped both single and double quotes. It converted

'   to   \' 

and 

"   to   \"

But it didn’t solve my problem because there was still javascript error. Single quotes problem was fixed but I realized that double quotes also needs to be HTML-escaped, not only Javascript-escaped.

Then I inserted the code below (escapeHtml function) to tags.tld for html escaping. I used escapeHtml method of org.apache.commons.lang.StringEscapeUtils class.

<taglib>
...
<function>
	<name>escapeHtml</name>
	<function-class>
		org.apache.commons.lang.StringEscapeUtils
	</function-class>
	<function-signature>
		java.lang.String escapeHtml(java.lang.String)
	</function-signature>
</function>
...
</taglib>

I solved this problem by using both escapeHtml and escapeJavaScript functions together in onclick event handler.

$('#photo_caption').text('${ch:escapeHtml(ch:escapeJavaScript(viewPhotoCaption))}');

escapeHtml function converted double quotes to html escaped double quotes.It converted

"  to  &quot;
Advertisements

About kaanmutlu

Software Developer - Computer Engineer from Istanbul, Turkey
This entry was posted in Uncategorized and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s