针对前端xss安全风险,利用DOMPurify清洗html字符串

319 阅读1分钟

1.基本用法

1.1 定义公共组件

以组件:

import DOMPurify from 'dompurify'

export default forwardRef(function Progress({ config }, ref) {
  const htmlRef = useRef()

  useEffect(() => {
    const clean = DOMPurify.sanitize(config.content, {
      USE_PROFILES: { html: true } //内置的html过滤配置
    })
    htmlRef.current.innerHTML = clean
  }, [config.content])
  return <div ref={htmlRef}></div>
})

以方法:

export const cleanHtml = ({content}) => {
  const clean = DOMPurify.sanitize(content, {
    USE_PROFILES: { html: true },
    ADD_ATTR: ['target']
  })

  return clean;
}

2.根据需求添加安全属性(不被过滤)

...
const clean = DOMPurify.sanitize(content, {
    USE_PROFILES: { html: true },
    ADD_ATTR: ['target'] // 额外允许放行的html属性
  })
...

更多配置可参考链接:www.npmjs.com/package/dom…