【问题标题】:How to make a Jsoup whitelist to accept certain attribute content如何让 Jsoup 白名单接受某些属性内容
【发布时间】:2014-04-22 01:20:03
【问题描述】:

我正在使用带有宽松白名单的 Jsoup。看起来很完美,但我想保留嵌入的图像标签,如<img alt="" src="data:;base64

有没有办法修改白名单以接受那些img?

编辑

如果我使用Whitelist.relaxed().addProtocols("img","src","data"),则不会删除这些 img 标签。但它接受“data:”之后的任何内容,如果 src 内容以“data:;base64”开头,我只想保留它们。用jsoup可以吗?

【问题讨论】:

  • 对我来说,我什至不必将它列入白名单来保留它。一些更多的源 HTML 可能和你的解析代码一样好。
  • Daniel:我正在使用 jsoup 1.7.2 和 Jsoup.clean(..., Whitelist.relaxed()。上述格式的任何类型的 img 都会被删除。

标签: java jsoup sanitization html-sanitizing


【解决方案1】:

您可以扩展白名单并覆盖 isSafeAttribute 以执行自定义检查。由于无法直接扩展 Whitelist.relaxed(),您必须复制一些代码来设置相同的列表:

public class RelaxedPlusDataBase64Images extends Whitelist {
    public RelaxedPlusDataBase64Images() {
        //copied from Whitelist.relaxed()
        addTags("a", "b", "blockquote", "br", "caption", "cite", "code", "col",
                "colgroup", "dd", "div", "dl", "dt", "em", "h1", "h2", "h3", "h4", "h5", "h6",
                "i", "img", "li", "ol", "p", "pre", "q", "small", "strike", "strong",
                "sub", "sup", "table", "tbody", "td", "tfoot", "th", "thead", "tr", "u",
                "ul");
        addAttributes("a", "href", "title");
        addAttributes("blockquote", "cite");
        addAttributes("col", "span", "width");
        addAttributes("colgroup", "span", "width");
        addAttributes("img", "align", "alt", "height", "src", "title", "width");
        addAttributes("ol", "start", "type");
        addAttributes("q", "cite");
        addAttributes("table", "summary", "width");
        addAttributes("td", "abbr", "axis", "colspan", "rowspan", "width");
        addAttributes("th", "abbr", "axis", "colspan", "rowspan", "scope", "width");
        addAttributes("ul", "type");
        addProtocols("a", "href", "ftp", "http", "https", "mailto");
        addProtocols("blockquote", "cite", "http", "https");
        addProtocols("cite", "cite", "http", "https");
        addProtocols("img", "src", "http", "https");
        addProtocols("q", "cite", "http", "https");
    }

    @Override
    protected boolean isSafeAttribute(String tagName, Element el, Attribute attr) {
        return ("img".equals(tagName)
                && "src".equals(attr.getKey())
                && attr.getValue().startsWith("data:;base64")) ||
            super.isSafeAttribute(tagName, el, attr);
    }
}

由于您没有提供用于解析的代码或您正在清理的 HTML,因此我没有对此进行测试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-14
    • 1970-01-01
    • 2016-07-07
    • 2013-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多