這是不行的,因爲CDATA不是一個標籤,它是一個實體,它通常屬於XML文檔而不是HTML文檔。如果你使用dig deep enough,你會看到Rails::Html::FullSanitizer
使用Loofah
,即它是#fragment
方法,它委託將傳遞的字符串解析爲HTML Document Fragment,它忽略了引擎蓋下的所有CDATA部分。
# === Rails::Html::FullSanitizer
# Removes all tags but strips out scripts, forms and comments.
#
# full_sanitizer = Rails::Html::FullSanitizer.new
# full_sanitizer.sanitize("<b>Bold</b> no more! <a href='more.html'>See more here</a>...")
# # => Bold no more! See more here...
class FullSanitizer < Sanitizer
def sanitize(html, options = {})
return unless html
return html if html.empty?
Loofah.fragment(html).tap do |fragment|
remove_xpaths(fragment, XPATHS_TO_REMOVE)
end.text(options)
end
end
因此,解決方案只是直接使用Loofah
,像這樣:
text = "<div>in div</div> just text <![CDATA[ in cdata ]]> <script>alert(1);</script> <form>some form</form> <!-- some comments also -->"
# => "<div>in div</div> just text <![CDATA[ in cdata ]]> <script>alert(1);</script> <form>some form</form> <!-- some comments also -->"
Loofah.scrub_xml_fragment(text, :prune).text
# => "in div just text in cdata some form "
這個代碼是什麼FullSanitizer
產生,因爲後者也刪除所有<form>
標籤,稍有不同的結果,當我代碼沒有。如果這對您至關重要,您可以將此代碼與上面的remove_xpaths
代碼結合使用(請參閱link)。
@Leo,請看看,讓我知道如果這段代碼修復你的問題。 – 2015-09-09 09:58:07
@ dodge901你在我的文章中發現如此令人反感嗎?我沒有膠水,請提出修改建議,我會很樂意接受它。 – 2015-09-14 16:37:43