Single Quotes, JavaScript, and Event Handlers

The Problem

Embedding event handlers in HTML elements that call JavaScript functions is a very common practice. Unfortunately Microsoft Internet Explorer 6 and 7 have a bug where single quote decimal references ( ' ) will be interpreted as single quote characters ( ' ), when in embedded JavaScript. This can easily cause issues where single quotes are being used as String constants, for example when passing arguments to JavaScript functions.

Effectively, the following code:

<a href="#addPage" onclick="WPCAPI.showAddPageDialog('bob&#039;sPage', 'Bob&#039;s Page');">

Will be interpreted as the following in Internet Explorer:

<a href="#addPage" onclick="WPCAPI.showAddPageDialog('bob'sPage', 'Bob's Page');">

Clearly, that will cause JavaScript errors at page load time.


The Solution

Make sure any single quotes in JavaScript argument values are either escaped or encoded appropriately. This must happen before the page is rendered, i.e. at compile time via Java, PHP, ASP.NET, etc. There are several options to choose from.


Render an escaped single quote character.<a href="#addPage" onclick="
WPCAPI.showAddPageDialog(
'bob\'sPage',
'Bob\'s Page'
);
">Add a Page</a>
Render a single quote decimal reference, escaping the leading "&". Ordinary HTML/XML escaping will convert single quotes to decimal references.<a href="#addPage" onclick="
WPCAPI.showAddPageDialog(
'bob\&#039;sPage',
'Bob\&#039;s Page'
);
">Add a Page</a>
Render a single quote hex reference. URL encoding will convert single quotes to hex references, but an additional JavaScript call will be necessary to decode the string before passing it to the listener.<a href="#addPage" onclick="
WPCAPI.showAddPageDialog(
decodeURIComponent('bob%27sPage'),
decodeURIComponent('Bob%27s Page')
);
">Add a Page</a>




elaine2
elaine2
Latest page update: made by elaine2 , May 16 2008, 9:36 PM EDT (about this update About This Update elaine2 Rename - elaine2

No content added or deleted.

- complete history)
More Info: links to this page
There are no threads for this page.  Be the first to start a new thread.

Related Content

  (what's this?Related ContentThanks to keyword tags, links to related pages and threads are added to the bottom of your pages. Up to 15 links are shown, determined by matching tags and by how recently the content was updated; keeping the most current at the top. Share your feedback on Wetpaint Central.)