26

How do I escape HTML with Jinja2 so that it can be used as a string in JavaScript (jQuery)?

If I were using Django's templating system I could write:

$("#mydiv").append("{{ html_string|escapejs }}");

Django's |escapejs filter would escape things in html_string (eg quotes, special chars) that could break the intended use of this code block, but Jinja2 does not seem to have an equivalent filter (am I wrong here?).

Is there a cleaner solution than copying/pasting the code from Django?

8

6 Answers 6

23

Jinja2 has nice filter tojson. If you make json from string, it will generate string enclosed in double quotes "". You can safely use it in javascript. And you don't need put quotes around by yourself.

$("#mydiv").append({{ html_string|tojson }});

It also escapes <>& symbols. So it is safe even when sting contains something XSS dangerous like <script>

0
15

This is a escapejs filter, based on Django's one, that I wrote for use in Jinja2 templates:

_js_escapes = {
        '\\': '\\u005C',
        '\'': '\\u0027',
        '"': '\\u0022',
        '>': '\\u003E',
        '<': '\\u003C',
        '&': '\\u0026',
        '=': '\\u003D',
        '-': '\\u002D',
        ';': '\\u003B',
        u'\u2028': '\\u2028',
        u'\u2029': '\\u2029'
}
# Escape every ASCII character with a value less than 32.
_js_escapes.update(('%c' % z, '\\u%04X' % z) for z in xrange(32))
def jinja2_escapejs_filter(value):
        retval = []
        for letter in value:
                if _js_escapes.has_key(letter):
                        retval.append(_js_escapes[letter])
                else:
                        retval.append(letter)

        return jinja2.Markup("".join(retval))
JINJA_ENVIRONMENT.filters['escapejs'] = jinja2_escapejs_filter

Example safe usage in a template:

<script type="text/javascript">
<!--
var variableName = "{{ variableName | escapejs }}";
…
//-->
</script>

When variableName is a str or unicode.

2
  • It is already required that {{ variableName | espacejs }} is in quotes (single or double) so square brackets tricks are not possible. Otherwise even a space could be dangerous.
    – Tometzky
    Commented Sep 21, 2013 at 7:25
  • 3
    This answer helped me out in this thread. Real mind bender to escape characters inside a string that are going to be printed from Python to HTML which is going to be inside quote tags inside JavaScript which is going to parse as JSON. Thnx for the help!
    – Matthisk
    Commented Mar 18, 2016 at 14:27
11

I faced a similar problem last year. Not sure whether you're using bottle, but my solution looked something like this.

import json

def escapejs(val):
    return json.dumps(str(val)) # *but see [Important Note] below to be safe

@app.route('/foo')
def foo():
    return bottle.jinja2_template('foo', template_settings={'filters': {'escapejs': escapejs}})

(I wrapped the template_settings dict in a helper function since I used it everywhere, but I kept it simple in this example.)

Unfortunately, it's not as simple as a builtin jinja2 filter, but I was able to live with it happily--especially considering that I had several other custom filters to add, too.

Important Note: Hat tip to @medmunds's for his astute comment below, reminding us that json.dumps is not XSS-safe. IOW, you wouldn't want to use it in a production, internet-facing server. Recommendation is to write a safer json escape routine (or steal django's--sorry OP, I know you were hoping to avoid that) and call that instead of using json.dumps.

5
  • Perfect! I'm not using bottle, I'm using pywebkitgtk to build a desktop app, but json.dumps is exactly what I needed. Much simpler than I'd hoped! Thank-you!
    – meshy
    Commented Sep 9, 2012 at 14:44
  • Oh, and thanks for the link to bottle! I've not seen that before, could come in handy ;)
    – meshy
    Commented Sep 9, 2012 at 14:48
  • 9
    I don't think json.dumps() escapes everything you need to worry about. E.g., as currently written, escapejs("</script>") returns "</script>" -- which seems like it could allow a closing script tag (and anything after it!) to leak into your html. (The Django escapejs filter does unicode escapes on the < and > characters, which avoids the problem.)
    – medmunds
    Commented Mar 8, 2013 at 20:11
  • 1
    ... yeah, seems like this answer definitely leaves an XSS vulnerability. Khan Academy has some examples here and provides their own escapejs and jsonify filters. Looks like they borrowed their implementation of escapejs from Django.
    – medmunds
    Commented Mar 8, 2013 at 20:34
  • @medmunds, thanks for pointing out the XSS vulnerability. You're right; I'll update the entry to point that out. (FWIW, in my case my service is internal, behind firewall, so XSS attack was not a top concern. I'll fix my code nevertheless, just to get in the right habit.) Commented Mar 9, 2013 at 5:43
1

I just researched this problem, my solution is to define a filter:

from flask import Flask, Markup
app = Flask(__name__)
app.jinja_env.filters['json'] = lambda v: Markup(json.dumps(v))

and in the template:

<script>
var myvar = {{myvar|json}} ;
</script>

This has the nice feature that myvar can be anything that can be JSON-serialised

1
  • 10
    Don't do this with user-generated content, as users will be able to execute JS. For example when myvar = </script><script>alert('XSS');
    – Blaise
    Commented Jul 15, 2016 at 12:14
0

Based on @tometzky here is my Python 3 version:

_js_escapes = {
        '\\': '\\u005C',
        '\'': '\\u0027',
        '"': '\\u0022',
        '>': '\\u003E',
        '<': '\\u003C',
        '&': '\\u0026',
        '=': '\\u003D',
        '-': '\\u002D',
        ';': '\\u003B',
        u'\u2028': '\\u2028',
        u'\u2029': '\\u2029'
}
# Escape every ASCII character with a value less than 32.
_js_escapes.update(('%c' % z, '\\u%04X' % z) for z in range(32))

@register.filter
def escapejs(value):
    return jinja2.Markup("".join(_js_escapes.get(l, l) for l in value))

The usage is exactly the same.

-1

You can also use jinja2's autoescape. So, for instance, you could add autoescape to your jinja2 Environment in Python:

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    autoescape=True)

Alternatively, you could use the Autoescape Extension added in Jinja 2.4 to have more control over where the autoescaping is used in the HTML. More information on this here and example (in Google App Engine) here.

Python:

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape'])

HTML:

{% autoescape true %}
    <html>
        <body>
            {{ IWillBeEscaped }}
        </body>
    </html>
{% endautoescape %}
2
  • 1
    Isn't this just standard HTML escaping? The question asks about Javascript?
    – pip
    Commented Nov 28, 2014 at 17:47
  • 2
    Nope, that definitely HTML escaping only. Commented Jan 2, 2015 at 18:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.