我正在使用 backbone,以及在页面加载时传递集合的一般方式
window.router = new Routers.ManageRouter({store: #{@store.to_json});
这很好并且运作良好,直到有人决定将文本“<script>alert("owned")</script>
”添加到商店字段之一。最后</script>
显然关闭了javascript。如何规避这种情况?
:javascript
$(function() {
window.router = new Dotz.Routers.ManageRouter({store: #{@store.to_json}});
Backbone.history.start();
});
以上输出:
<script>
//<![CDATA[
$(function() {
window.router = new Dotz.Routers.ManageRouter({store: '{"_id":"4f3300e19c2ee41d9a00001c", "points_text":"<script>alert(\"hey\");</script>"'});
Backbone.history.start();
});
//]]>
</script>
最佳答案
在 <script>
里面阻止它是syntactically illegal有任何 </
后跟一个名字——不仅仅是</script>
——所以你需要在它可能出现的任何地方逃避它。例如:
:javascript
var foo = { store: #{@store.to_json.gsub('</','<\/')} };
这将创建序列 <\/
在你的 JS 字符串中,它被解释为与 </
相同.确保在 gsub 替换字符串中使用单引号,否则使用 gsub( "</", "<\\/" )
由于 Ruby 中单引号和双引号的区别。
实际显示:
irb:02.0> s = "<b>foo</b>" # Here's a dangerous string
#=> "<b>foo</b>"
irb:03.0> a = [s] # Wrapped in an array, for fun.
#=> ["<b>foo</b>"]
irb:04.0> json = a.to_json.gsub( '</', '<\/' ) # Sanitized
irb:05.0> puts json # This is what would come out in your HTML; safe!
#=> ["<b>foo<\/b>"]
irb:06.0> puts JSON.parse(json).first # Same as the original? Yes! Yay!
#=> <b>foo</b>
如果您使用的是 Rails(或 ActiveSupport),您可以启用 JSON escaping :
ActiveSupport::JSON::Encoding.escape_html_entities_in_json = true
实际可见:
irb:02.0> a = ["<b>foo</b>"]
irb:03.0> puts a.to_json # Without the magic
#=> ["<b>foo</b>"]
irb:04.0> require 'active_support'
irb:05.0> ActiveSupport::JSON::Encoding.escape_html_entities_in_json = true
irb:06.0> puts a.to_json # With the magic
#=> ["\u003Cb\u003Efoo\u003C/b\u003E"]
它生成的 JSON 比您解决此特定问题所需的更冗长,但它是有效的。
关于javascript - 在 javascript 中转义 </script> 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9246382/