gpt4 book ai didi

html - 在 ActionView::Base.full_sanitizer 中允许 CDATA

转载 作者:数据小太阳 更新时间:2023-10-29 09:03:33 25 4
gpt4 key购买 nike

我正在删除众所周知的 html 内容

ActionView::Base.full_sanitizer.sanitize(value)

方法。然而,当 value传递给方法的包裹在 <![CDATA[ 中和 ]]>返回值为空。如何防止此方法对 CDATA 作出 react ?

我尝试将其放入 application.rb

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

但是没用

最佳答案

这行不通,因为 CDATA不是标签,是实体,通常属于XML文档而不是HTML文档。如果你dig deep enough , 你会看到 Rails::Html::FullSanitizer使用 Loofah 在引擎盖下,即它是#fragment委托(delegate)将传递的字符串解析为 HTML 文档片段的方法,它忽略了引擎盖下的所有 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 )。

关于html - 在 ActionView::Base.full_sanitizer 中允许 CDATA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29364552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com