Opened 3 years ago

Closed 2 years ago

#21731 closed Bug (fixed)

django.utils.text.javascript_quote does not escape "</" (without double quotes)

Reported by: vajrasky Owned by: vajrasky
Component: Utilities Version: master
Severity: Normal Keywords:
Cc: sky.kok@…, yokomizor Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


For the uninitiated, javascript_quote is useful if you want to add dynamic text to javascript.

Consider this case:

  <div id="reviews"></div>
  <script type="text/javascript">
    $("#reviews").append("{{ dynamic_text }}");

The dynamic text could be:

<a href='controller/action'>Action!</a>

So the relevant section of the template would be:

$("#reviews").append('<a href='controller/action'>Action!</a>');

As you can see the javascript code will break because of single quotes inside single quotes. But with javascript_quote, the relevant section of the template would be:

$("#reviews").append('<a href=\'controller/action\'>Action!</a>');

So all is well!

Well, not really. The javascript_quote only escapes carriage returns and single and double quotes and backslashes. But this is not enough. It needs to escape "</" (without double quotes) as well. Consider this case:

$("#reviews").append('<script>alert("Manly man loves cute cat");</script>');

The "</script>" (without double quotes) will break the javascript code. It is the closing tag of javascript code in html. In fact, Rails escapes "</" (without double quotes).

Change History (3)

comment:1 Changed 3 years ago by vajrasky

  • Cc sky.kok@… added
  • Has patch set
  • Needs documentation unset
  • Needs tests unset
  • Owner changed from nobody to vajrasky
  • Patch needs improvement unset
  • Status changed from new to assigned

PR is here:

Anyway javascript_quote name is misleading. Probably the name escape_for_javascript is better.

comment:2 Changed 3 years ago by yokomizor

  • Cc yokomizor added
  • Triage Stage changed from Unreviewed to Ready for checkin

comment:3 Changed 2 years ago by Tim Graham <timograham@…>

  • Resolution set to fixed
  • Status changed from assigned to closed

In c43c469a2e4633361f5dccf7dc7ce37054008d18:

Fixed #21731 -- Made javascript_quote escapes '</'.

Note: See TracTickets for help on using tickets.
Back to Top