在javascript中转义标记

时间:2012-02-12 04:12:55

标签: javascript ruby-on-rails ruby backbone.js haml

我使用骨干网,以及在页面加载

时传递集合的一般方法
window.router = new Routers.ManageRouter({store: #{@store.to_json});

这很好,效果很好,直到有人决定添加文字&#34; <script>alert("owned")</script>&#34;到其中一个商店领域。最后</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>

3 个答案:

答案 0 :(得分:15)

<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比解决这个特定问题所需的更冗长,但是它很有效。

答案 1 :(得分:4)

神奇的词是:

ActiveSupport.escape_html_entities_in_json = true

虽然标记为已弃用,但仍可在当前的rails版本中使用(请参阅我的rails c):

ruby-1.9.3-head :001 > ::Rails.version
 => "3.2.1" 
ruby-1.9.3-head :002 > ["<>"].to_json
 => "[\"<>\"]" 
ruby-1.9.3-head :003 > ActiveSupport.escape_html_entities_in_json = true
 => true 
ruby-1.9.3-head :004 > ["<>"].to_json
 => "[\"\\u003C\\u003E\"]" 

答案 2 :(得分:-1)

你忘记了''

:javascript
    $(function() {
      window.router = new Dotz.Routers.ManageRouter({store: '#{@store.to_json}'});
      Backbone.history.start();
    });