How to safely inject HTML in React using an iframe

Mauro Alvarez
Dec 13, 2019 · 3 min read

If you need to inject HTML into your React app and you don’t want to use dangerouslySetInnerHTML (in most cases you shouldn’t
;-P ) because isn’t safe, this article is for you.

Why (in most cases) you shouldn’t use dangerouslySetInnerHTML

As the react documentation says

dangerouslySetInnerHTML is React’s replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack.

In fewer words, dangerouslySetInnerHTML isn’t safe.

Why?

The problem with this is that the HTML you are injecting to your app could be malformed, it could have CSS/JS that breaks your app, or even worse, JS that steals data from your app.

How to make an iframe secure?

You should avoid using both allow-scripts and allow-same-origin, as that lets the embedded document remove the sandbox attribute — making it no more secure than not using the sandbox attribute at all.

How to inject and update the content in an iframe?

  • by using the iframe attribute srcdoc (which is not supported by IE and Edge)
  • by using the iframe.document.open()/write()/close()

Using srcdoc

Unfortunately srcdoc isn’t supported in IE and Edge. There is a polyfill but it isn’t useful in this case because it requires allow-scripts (and remember that’s not safe)

Using iframe.document.open()/write()/close()


Conclusion

Drop a comment below or start a conversation with the author in Twitter on what you think about this article.

Thinkmill

A collection of posts by the team at Thinkmill

Thanks to Calum Gathergood

Mauro Alvarez

Written by

An Argentinian-Australian Software engineer. Currently living in Sydney, Australia 🇦🇺. Working @thinkmill and as a contractor @atlassian.

Thinkmill

Thinkmill

A collection of posts by the team at Thinkmill

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade