10

我试过使用Sanitize gem来清理包含网站HTML的字符串。删除HTML页面中的所有JavaScript

它只删除了<script>标记,而不是脚本标记中的JavaScript。

我可以使用什么从页面中删除JavaScript?

+2

您是否还想删除所有'on *'属性? – Phrogz

回答

5

我对偏爱Loofah gem。从一个例子中的文档修改:

1.9.3p0 :005 > Loofah.fragment("<span onclick='foo'>hello</span> <script>alert('OHAI')</script>").scrub!(:prune).to_s 
=> "<span>hello</span> " 

你可能会感兴趣的ActiveRecord extensions丝瓜提供。

13
require 'open-uri'  # included with Ruby; only needed to load HTML from a URL 
require 'nokogiri'  # gem install nokogiri read more at http://nokogiri.org 

html = open('http://stackoverflow.com')    # Get the HTML source string 
doc = Nokogiri.HTML(html)       # Parse the document 

doc.css('script').remove        # Remove <script>…</script> 
puts doc            # Source w/o script blocks 

doc.xpath("//@*[starts-with(name(),'on')]").remove # Remove on____ attributes 
puts doc            # Source w/o any JavaScript 
+0

如果您的目的是防止XSS攻击,这似乎是一个非常糟糕的主意。有各种你缺少的边缘情况。 https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet – Ajedi32

6

事实证明,Sanitize内置了(只是没有很好的记载)的选项...

Sanitize.clean(content, :remove_contents => ['script', 'style']) 

此删除了所有的脚本和风格标签(和内容),因为我想要的。

0

所以,你需要的sanitize宝石添加到您的Gemfile:

gem 'sanitize` 

然后bundle

然后你就可以做Sanitize.clean(text, remove_contents: ['script', 'style'])

0

我用这个正则表达式摆脱<script></script>标签嵌入的内容,只是使标签消失。它也摆脱了诸如< script></script>等...的东西,即增加了空格。

post.content = post.content.gsub(/<\s*script\s*>|<\s*\/\s*script\s*>/, '')

相关问题