2016-03-01 47 views
1

在Rails中,我看到
+ html_escape:escape all tags。
+清理:删除所有不在while列表中的标签。Rails - 如何逃生<script>标签

现在,我只想逃避脚本标记,而不是escapse其他标记。

您有解决方案吗?谢谢大家!

+0

您正在使用哪种版本的导轨? –

+0

使用导轨的Iam 4.2.5 – user3418135

+0

请参阅此链接。 http://stackoverflow.com/questions/35625464/how-to-show-some-html-entities-on-title-tag-using-rails/35626493#35626493 – VtrKanna

回答

0
string = '<html> <title> <head> <script type="javascript"></script> </head> </title> </html>' 

string.gsub(/<script.*[\s\S]*\/script>/,"") 

=> "<html> <title> <head> </head> </title> </html>" 

更新

如果您使用Rails 4.2.5,你可能需要这个。

Rails::HTML::TargetScrubber

0
string.gsub!(/<(?=script)||(?<=script)>/) {|x| "#\{x}"} 
+0

有关解释的一些解释将有助于了解更多信息。 – Laas

0

的Rails提供串/ HTML实体这么多的选择

s = "<script>alert('Hello');</script>" 

选项:WhiteListSanitizer

white_list_sanitizer = Rails::Html::WhiteListSanitizer.new 
white_list_sanitizer.sanitize(s, tags: %w()) 
white_list_sanitizer.sanitize(s, tags: %w(table tr td), attributes: %w(id class style)) 
    => "alert('Hello');" 

请参考以下链接ALSE

How to show some HTML entities on title tag using Rails

0

由于您在导轨4.2.5上,因此您可以使用通过导轨安装的https://github.com/rails/rails-html-sanitizer。您可以执行以下操作来只转义脚本标记。

scrubber = Rails::Html::TargetScrubber.new 
scrubber.tags = ['script'] 

html_fragment = Loofah.fragment('<script></script><div></div>') 
html_fragment.scrub!(scrubber) 
html_fragment.to_s # o/p "div></div>"