【问题标题】:How to allow svg elements using the new Sanitize api如何使用新的 Sanitize api 允许 svg 元素
【发布时间】:2022-10-07 22:07:00
【问题描述】:

https://developer.mozilla.org/en-US/docs/Web/API/HTML_Sanitizer_API

使用 html sanitizer api,即使我将它添加到允许列表中,它也会删除“svg”标签。我怎样才能允许'svg'标签?

目前使用的是 chrome 105。

const cfg = Sanitizer.getDefaultConfiguration();
cfg.allowCustomElements = true;
cfg.allowElements.push('svg');
cfg.allowElements.push('slot');
cfg.allowElements.push('path');
const sanitizer = new Sanitizer(cfg)
const str = `<button>
        <svg viewBox="0 0 24 24">
            <path d="M7.41,8.58L12,13.17L16.59,8.58L18,10L12,16L6,10L7.41,8.58Z"></path>
        </svg>
</button>`

const container = document.createElement('div')
container.setHTML(str, {sanitizer: sanitizer})

消毒剂正在删除 svg 标签和里面的所有东西。 常量 hasSvg = cfg.allowElements.includes('svg'); // 返回真

【问题讨论】:

  • 也许与this 有关,虽然我不知道具体是怎么做的

标签: javascript html google-chrome htmlsanitizerapi sanitizerapi


【解决方案1】:

这是一个实验性功能,支持很差。此外,它仅适用于 HTTPS 协议。也就是说,您不能通过常规 localhost 使用它。 您必须等待更长的时间才能大胆使用。

请改用purify-html 库。它适用于更常见的浏览器 API,非常轻量级(MINIFIED + GZIPPED - 462 字节!)并且可以安全地删除危险标签。

【讨论】:

    猜你喜欢
    • 2016-05-17
    • 1970-01-01
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2014-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多