Escaped JavaScript quotes in HTML (Pitfall)

Closing quotes may appear when you least expect them.

If you are generating JavaScript calls from a database, you might use one particular field as a quote delimited text parameter like this:

<A HREF="javascript:alert('Some text');">Click me</A>

Since the JavaScript call is inside a tag attribute, it is enclosed in double quotes. This means for starters that double quotes are a problem in your data if they appear.

You can get round this by enclosing any string constants in the JavaScript domain by using single quotes. JavaScript doesn't mind either. However, that means you get a problem when a single quote turns up in your data.

You might think that your output routines that get data from the database are doing very well by detecting the apostrophe and replacing it with &#039;, however you might still be in trouble. Likewise if you escaped the double quote by using the HTML character entity descriptor. This is because the browser unescapes the page as it is loaded. This is extremely hard to diagnose because when you view the source, you see the character entities and not the characters they become.

You must ensure that your data extraction/insertion code places the database generated items into this scenario with JavaScript escapes and not HTML escapes.

Of course everywhere else in the document you need to escape things as HTML and not JavaScript.

This all applies vice versa by swapping the quotes around, although the escaped character entity value changes.

The example code illustrates a set of quoted strings that break and another set that work fine.

When they break, they cause a run-time error. In some cases they even prevent the status line from displaying the right thing.

Example code:

   Watch the status bar as you roll over the link.<BR>
   Examples of broken quotes:<BR>
   <A HREF="javascript:alert('xxx'xxx');">Test 1.1</A><BR>
   <A HREF="javascript:alert('xxx&#039;xxx');">Test 1.2</A><BR>
   <A HREF='javascript:alert("xxx"xxx");'>Test 1.3</A><BR>
   <A HREF='javascript:alert("xxx&#034;xxx");'>Test 1.4</A><BR>
   <A HREF='javascript:alert("xxx\'xxx");'>Test 1.5</A><BR>
   <A HREF="javascript:alert('xxx\"xxx');">Test 1.6</A><BR>
   These work fine:<BR>
   <A HREF="javascript:alert('xxx\'xxx');">Test 2.1</A><BR>
   <A HREF='javascript:alert("xxx\"xxx");'>Test 2.2</A><BR>
   <A HREF="javascript:alert('xxx&#034;xxx');">Test 2.3</A><BR>
   <A HREF='javascript:alert("xxx&#039;xxx");'>Test 2.4</A><BR>
   <A HREF="javascript:alert('xxx\047xxx');">Test 2.5</A><BR>
   <A HREF="javascript:alert('xxx\x27xxx');">Test 2.6</A><BR>
   <A HREF="javascript:alert('xxx\u0027xxx');">Test 2.7</A><BR>
   <A HREF="javascript:alert('xxx\042xxx');">Test 2.8</A><BR>
   <A HREF="javascript:alert('xxx\x22xxx');">Test 2.9</A><BR>
   <A HREF="javascript:alert('xxx\u0022xxx');">Test 2.10</A><BR>

See also:HTML Character entity, Pitfalls, String literal