如何使用新HTML Sanitizer API允许SVG元素?
解决HTML Sanitizer API允许SVG标签的问题
问题出在SVG元素属于SVG命名空间,直接将'svg'字符串加入allowElements数组时,Sanitizer会把它当作HTML命名空间的元素处理,而SVG标签本身不属于HTML命名空间,因此仍会被过滤移除。
正确的配置方式是为SVG相关元素指定对应的命名空间:
const cfg = Sanitizer.getDefaultConfiguration(); // 为SVG元素添加命名空间声明,替换原直接push字符串的方式 cfg.allowElements.push( { name: 'svg', namespace: 'http://www.w3.org/2000/svg' }, { name: 'path', namespace: 'http://www.w3.org/2000/svg' }, 'slot' // slot是HTML标准元素,直接用字符串即可 ); // 无需开启allowCustomElements,SVG不属于自定义元素 // cfg.allowCustomElements = true; 可移除该行 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内部元素(如
path、circle、rect等)都需要指定SVG命名空间才能被保留。 allowCustomElements仅针对自定义元素生效,开启它对SVG元素的过滤无帮助,反而可能引入不必要的逻辑。
内容的提问来源于stack exchange,提问作者Eric Rohlfs
相关产品推荐
相关产品推荐

