如何安全地在响应中呈现HTML? [英] How to safely render html in react?

查看:78
本文介绍了如何安全地在响应中呈现HTML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从文本区域得到了一些用户生成的html标记,我想在屏幕的另一部分上呈现它.标记将以字符串形式保存在组件的属性中.

I've got some user generated html markup from a text area and I'd like to render it on another part of the screen. The markup is saved as a string in the props of the component.

出于明显的原因,我不想使用危险地设置html.是否有诸如已标记之类的解析器,但对于html来说,这样可以使脚本标记和其他无效的html消失.

I don't want to use dangerouslysethtml for obvious reasons. Is there a parser such as marked but for html so that it strips out script tags and other invalid html.

推荐答案

使用对HTML进行消毒-html 模块,并使用 dangerouslySetInnerHTML呈现清理过的字符串.

您可以创建一个简单的包装器组件:

You can create a simple wrapper component:

const defaultOptions = {
  allowedTags: [ 'b', 'i', 'em', 'strong', 'a' ],
  allowedAttributes: {
    'a': [ 'href' ]
  },
  allowedIframeHostnames: ['www.youtube.com']
};

const sanitize = (dirty, options) => ({
  __html: sanitizeHtml(
    dirty, 
    options: { ...defaultOptions, ...options }
  )
});

const SanitizeHTML = ({ html, options }) => (
  <div dangerouslySetInnerHTML={sanitize(html, options)} />
);

用法:

<SanitizeHTML html="<img src=x onerror=alert('img') />" />


您还可以使用 react-sanitized-html 的SanitizedHTML组件,这是sanitize-html周围的一个反应包装:


You can also use react-sanitized-html's SanitizedHTML component, which is a react wrapper around sanitize-html:

<SanitizedHTML
  allowedAttributes={{ 'a': ['href'] }}
  allowedTags={['a']}
  html={ `<a href="http://bing.com/">Bing</a>` }
/>

这篇关于如何安全地在响应中呈现HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆