How to safely embed JSON with </script> in HTML document?
Your code using just @tags.to_json
works in rails3, if you enable it with:
ActiveSupport.escape_html_entities_in_json = true
Otherwise, your other option is this:
var tags_list = <%= raw @tags.to_json.gsub("</", "<\\/") %>;
This saves the client having to parse the whole thing through $
The proper way in 2019 is to wrap obj.to_json
with json_escape
function. json_escape
is directly intended for escaping specific HTML symbols inside JSON strings. Example below from the documentation:
json = JSON.generate({ name: "</script><script>alert('PWNED!!!')</script>"})# => "{\"name\":\"</script><script>alert('PWNED!!!')</script>\"}"json_escape(json)# => "{\"name\":\"\\u003C/script\\u003E\\u003Cscript\\u003Ealert('PWNED!!!')\\u003C/script\\u003E\"}"JSON.parse(json) == JSON.parse(json_escape(json))# => true
It seems this page appears on top of Google Search results, that's why I decided to provide a comment with an update :)
btw, this works but is not a good solution in my opinion:
<script type="text/javascript" charset="utf-8"> //<![CDATA[ var tags_list = <%=raw @tags.to_json.gsub('/', '\/') %>; // ]]></script>