简体   繁体   中英

How do I SAFELY render Markdown from a React component?

I want to display markdown in my ReactJS app, but its important that it's done safely. The markdown files I will be displaying are untrusted public content.

I've seen various solutions and they all use dangerouslySetInnerHTML.

I can't help thinking that this might be, well, dangerous.

Anyone have any ideas?

thanks

They gave dangerouslySetInnerHTML a scary name very deliberately , to make sure people would think very carefully about whether they needed to use it/whether they were using it correctly. Seeing as you're asking this question, clearly it's done that job pretty well! But Markdown rendering is in fact one instance where it's necessary.

Basically, what it comes down to is: dangerouslySetInnerHTML is only dangerous when you don't make sure the stuff you're putting into it is safe beforehand. Be careful, but don't be scared off by it!

EDIT: As mentioned by Waylan in the comments, the example I gave was pretty naive and didn't take into account other ways XSS attacks can be achieved through Markdown . Most likely you're going to want to run the output through a sanitizer instead of/as well as the input, otherwise it's very possible to generate malicious HTML without doing something as straightforward as just embedding a script tag. The main point of my answer remains the same though; dangerouslySetInnerHTML is only as dangerous as what you put into it. Do your research, make sure the input is safe, and you'll be fine.

If the input is not trusted (and you can't do anything about it) the library should sanitize the input properly before displaying it.

I have found two libraries that seem to do that:

  • react-markdown

    Just make sure that escapeHtml option is set to true . To test, set "HTML mode" to "Escape" on demo page .

  • remarkable

    Didn't test it, and safety is not "an explicitly stated goal of the project". The information is from 2014 though, so that might have changed (no info in README). YMMV.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM