javascript - 在 javascript 中转义 </script> 标签

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

我正在使用 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 中转义 &lt;/script&gt; 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9246382/

相关文章:

javascript - 将值传递给嵌套的 parse.com 查询回调

javascript - 即使安装了 Node,也无法在 Node 中加载 Axios

javascript - 使用 pstricks 和 latex2html5 绘制圆弧

ruby-on-rails - 如何在 Rails 4 中测试 Controller 问题

ruby-on-rails - Ruby on Rails 和 Active Record - 查找没有出现在给定 y 中的所有 x

ruby-on-rails - rake 数据库 :create vs rake db:create:all

ruby - Sass 使用 Ruby - '"“C :\Program' is not recognized as an internal or external command

javascript - 将 d3 层次结构(d3 树)图反转到左侧以也显示下游

c++ - 将 SWIG 与 C++ 模板函数结合使用

ruby-on-rails - ActiveRecord 为 has_many 生成的错误 sql :through relation with STI