views:

65

answers:

2

I'm having a problem passing parameters that I think I should be able to solve elegantly (with 1 line of code) but I can't seem to solve the issue. I have a link to delete items, like so:

<a href="javascript:confirmDelete('${result.headline}',${result.id});">

The problem arises when result.headline contains characters like ' or " or others that break the javascript call. I have tried ${fn:replace(result.headline,"'","")} which fixes issues for ' however I want to do some sort of URLEncode (I think) so that these characters dont break the javascript call. Any ideas on how to fix this without changing anything on the back-end?

A: 

As long as you can rely on the fact that the strings don't have newlines, all you need to do is double all backslashes and escape all single quotes.

For example:

replace(replace(result.headline, "\\", "\\\\"), "'", "\\'")

This might not be valid syntax in your server-side language; I don't recognize it.

SLaks
+3  A: 

Avoid putting inline JavaScript in elements, especially javascript: pseudo-URLs which (apart from being Evil that should never be used) are JavaScript-in-URL-in-HTML. You would have to take the headline and:

  1. JavaScript string literal-encode it. (Replacing \, ', control characters and potentially Unicode characters, or just using a JSON encoder to do it for you.) Then,
  2. URL-encode it. Then,
  3. HTML-encode it.

Better to put the data in the markup where you only have to worry about simple HTML encoding in the way you do everywhere else to avoid cross-site-scripting:

<a href="#" class="confirmdelete-${fn:escapeXml(result.id)}" title="${fn:escapeXml(result.headline)}">Delete</a>

and have the JavaScript extract them:

<script type="text/javascript">
    for (var i= document.links.length; i-->0;) {
        var link= document.links[i];
        if (link.className.indexOf('confirmdelete-')===0) {
            link.onclick= function() {
                confirmDelete(this.title, this.className.substring(14));
                return false;
            };
        }
    }
</script>

(there are potentially simpler, shorter or cleaner ways of writing the above using utility functions or frameworks, and there's an argument to be had over whether a link is really the right markup for this kind of action, but that's the basic idea.)

bobince
Im trying to implement this answer but have a problem. I can confirm that the link.onclick is being set, but when I click the link, there is no action. Any ideas why this might be happening?
UmYeah
Check the console for JavaScript errors, and put some `alert('hello')` calls in the onclick function so you can see how far it's getting?
bobince