Skip to content Skip to sidebar Skip to footer

Escape Possible Quotes In String Passed To A Js Function In A Onclick Event

I have the following cycle in a jspx:
  • Solution 1:

    You should do it in the server side, not in the client side. Doing it in the client side is too late anyway. Depending on the sole purpose of the value, whether it's going to be used as part of HTML and doesn't contain linebreaks, or as JS code, you can use either the JSTL-provided EL function fn:escapeXml()

    <%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
    ...
    <a onclick="myFunct('${var.url}','${fn:escapeXml(var.title)}','${fn:escapeXml(var.descr)}');">
    

    or create a custom EL function which uses Apache Commons Lang StringEscapeUtils#escapeJavaScript() under the covers.

    <%@taglib prefix="my" uri="http://example.com/functions" %>
    ...
    <a onclick="myFunct('${var.url}','${my:escapeJs(var.title)}','${my:escapeJs(var.descr)}');">
    

    You can find a concrete example how to create an EL function at the bottom of this answer.

    I guess that it's going to be used as part of HTML, so fn:escapeXml() could to be sufficient.

    Solution 2:

    You don't need to create your own EL function but use apache-commons directly from your custom .tld:

    <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>
    

    Solution 3:

    I suggest you encode on the server http://www.roseindia.net/jsp/jsp-url-encoding.shtml

    or store the stuff in a hidden element

    <span id="url" style="display:none">${var.URL}</span>
    <span id="title" style="display:none">${var.title}</span>
    <span id="desc" style="display:none">${var.descr}</span>
    

    and do onClick="return myFunct(['url','title','desc'])">...</a>

    functionmyFunct(parms) {
      var url   = parms[0]?document.getElementById(parms[0]).innerHTML:"No url";
      var title = parms[1]?document.getElementById(parms[1]).innerHTML:"No title";
      var descr = parms[2]?document.getElementById(parms[2]).innerHTML:"No description";
      returnfalse;
    }
    

    Solution 4:

    You need to pass a valid JavaScript String literal to myFunct. escape is a JavaScriptfunction that expects a valid String as well. You thus need to transform you Java String into a valid JavaScript literal. Use apache commons-lang StringEscapeUtils.escapeECMAScript to escape it. You could make it an EL function, and thus use something like

    onClick="myFunct('${myFn:escapeJs(var.url)}','${myFn:escapeJs(var.title)}, '${myFn:escapeJs(var.descr)}');"
  • Post a Comment for "Escape Possible Quotes In String Passed To A Js Function In A Onclick Event"