I want to diplay html content in the browser without escaping it.my code is as below.
我想在浏览器中显示html内容而不转义它。我的代码如下所示。
<% @mydata = "<p>paragraph</p><h1>Test</h1><script>alert('got your cookie')</script><h1>another test</h1>" %>
<%= sanitize @mydata %>
here i can't use raw method because raw
method will execute malicious javascript code and hence i am using rails sanitize
method. but the problem is that rails sanitize method deleting <script>alert('got your cookie')</scipt>
line and not showing it in the browser.
在这里我不能使用原始方法,因为原始方法将执行恶意javascript代码,因此我使用rails sanitize方法。但问题是rails清理方法删除
I am getting output as below
我得到如下输出
paragraph
My expected output is as below
我的预期产量如下
paragraph
is there any way to unescape html content and escape only javascript content from the user input?
是否有任何方法来unescape html内容并从用户输入中仅转义javascript内容?
Thanks,
0
in rails you can whitelist tags:
在rails中你可以将标签列入白名单:
<%= sanitize @comment.body, tags: %w(strong em a), attributes: %w(href) %>
option 1
require 'cgi'
CGI.escapeHTML('<h1>hi</h1><script>aeuoau</script>')
# => "<h1>hi</h1><script>aeuoau</script>"
option 2
if you are building something like blog website where you would display html code:
如果你正在构建像博客网站,你将显示HTML代码:
option 3
if you just want to remove malicious HTML and keep common text tags like p
, b
, ul
, ....
如果你只想删除恶意HTML并保留常见的文本标签,如p,b,ul,....
raw(simple_format('<h1>hi</h1><script>aeuoau</script>'))
# => "<p><h1>hi</h1>aeuoau</p>"
http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-simple_format
note: simple_format will "format" your code => would wrap \n
in <p></p>
, etc.
注意:simple_format将“格式化”你的代码=>将在
中包裹\ n等。
other gems
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2016/05/13/70d8f8e465c65bd1d6755effa0257cc8.html。