Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape JavaScript in Expression Language

Sometimes, I need to render a JavaScript variable using EL in a JSF page.

E.g.

<script>var foo = '#{bean.foo}';</script>

or

<h:xxx ... onclick="foo('#{bean.foo}')" />

This fails with a JS syntax error when the EL expression evaluates to a string containing JS special characters such as apostrophe and newline. How do I escape it?

like image 977
Ontonomo Avatar asked Jul 07 '11 21:07

Ontonomo


People also ask

How do you escape JavaScript?

Using the Escape Character ( \ ) We can use the backslash ( \ ) escape character to prevent JavaScript from interpreting a quote as the end of the string. The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string.

How do you escape a special character in JavaScript?

To use a special character as a regular one, prepend it with a backslash: \. . That's also called “escaping a character”.

What can I use instead of escape in JavaScript?

JavaScript escape() The escape() function is deprecated. Use encodeURI() or encodeURIComponent() instead.


1 Answers

You can use Apache Commons Lang 3.x StringEscapeUtils#escapeEcmaScript() method for this in EL.

First create a /WEB-INF/functions.taglib.xml which look like this:

<?xml version="1.0" encoding="UTF-8"?>
<facelet-taglib 
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facelettaglibrary_2_0.xsd"
    version="2.0">
    <namespace>http://example.com/functions</namespace>

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

Then register it in /WEB-INF/web.xml as follows:

<context-param>
    <param-name>javax.faces.FACELETS_LIBRARIES</param-name>
    <param-value>/WEB-INF/functions.taglib.xml</param-value>
</context-param>

Then you can use it as follows:

<html ... xmlns:func="http://example.com/functions">
...
<script>var foo = '#{func:escapeJS(bean.foo)}';</script>
...
<h:xxx ... onclick="foo('#{func:escapeJS(bean.foo)}')" />

Alternatively, if you happen to already use the JSF utility library OmniFaces, then you can also just use its builtin of:escapeJS() function:

<html ... xmlns:of="http://omnifaces.org/functions">
...
<script>var foo = '#{of:escapeJS(bean.foo)}';</script>
...
<h:xxx ... onclick="foo('#{of:escapeJS(bean.foo)}')" />
like image 103
BalusC Avatar answered Oct 05 '22 19:10

BalusC