2015-03-31 30 views
2

我刪除HTML的東西與知名的ActionView允許CDATA :: Base.full_sanitizer

ActionView::Base.full_sanitizer.sanitize(value) 

方法。但是,它的效果很好,當value傳入的方法被包裝在<![CDATA[]]>返回值爲空時。我怎樣才能防止這種方法對CDATA作出反應?

我試過是把這個application.rb中

config.action_view.sanitized_allowed_tags = ["![CDATA[", "]]"] 

內,但它不工作

回答

2

這是不行的,因爲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)。

+0

@Leo,請看看,讓我知道如果這段代碼修復你的問題。 – 2015-09-09 09:58:07

+0

@ dodge901你在我的文章中發現如此令人反感嗎?我沒有膠水,請提出修改建議,我會很樂意接受它。 – 2015-09-14 16:37:43