[英]Escaping </script> tag inside javascript
我正在使用骨干,以及在頁面加載時傳遞集合的一般方法
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>
塊中,任何</
后跟一個名稱 - 不僅僅是</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轉義 :
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比解決這個特定問題所需的更冗長,但它是有效的。
神奇的詞是:
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\"]"
你忘記了''
:javascript
$(function() {
window.router = new Dotz.Routers.ManageRouter({store: '#{@store.to_json}'});
Backbone.history.start();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.