- How to Load HTML, CSS, and JS Code into an iFrame
- Attempt #1: Using srcdoc
- 1. Browser Support for srcdoc is not great
- 2. It’s possible to «escape» from CSS/JS
- Attempt #2: Serverless Boomerang
- Attempt #3: Serverless Boomerang (redux)
- Solution: Blob URLs
- Blobs
- The Moral?
- 2 Ways To Add HTML Code In Javascript (A Quick Guide)
- TLDR – QUICK SLIDES
- TABLE OF CONTENTS
- WAYS TO ADD HTML CODE
- METHOD 1) DIRECTLY CHANGE HTML CODE
- METHOD 2) CREATE & APPEND HTML ELEMENTS
- MORE HTML SELECTION & INSERTION
- GET HTML ELEMENTS IN JAVASCRIPT
- SET HTML/CSS PROPERTIES
- TAKE EXTRA NOTE OF THE LOADING ORDER!
- DOWNLOAD & NOTES
- SUPPORT
- EXAMPLE CODE DOWNLOAD
- EXTRA BITS & LINKS
- DIRECT HTML MANIPULATION VS CREATING OBJECTS
- RECOMMENDED READS
- TUTORIAL VIDEO
- INFOGRAPHIC CHEAT SHEET
- THE END
- Leave a Comment Cancel Reply
- Search
- Breakthrough Javascript
- Socials
- About Me
How to Load HTML, CSS, and JS Code into an iFrame
If you’re just here for the answer, not the story, the solution is at the bottom. If you’ve ever used JSFiddle, Codepen, or others, this problem will be familiar to you: The goal is to take some HTML, CSS, and JS (stored as strings) and create an iframe with the code loaded inside. This problem should be easy, but it isn’t. At least. It wasn’t, until I found the golden ticket I had been waiting for all along. But more on that later. Let’s start with all the things that didn’t work, because that’s more fun.
Attempt #1: Using srcdoc
After doing a bit of research, I was thrilled to discover that it’s possible to add a srcdoc attribute to iframes. If you pass in an HTML string, the iframe will load with that HTML content inside:
srcdoc="This text will appear in the iframe!
">
1. Browser Support for srcdoc is not great
If we want to support IE or Edge, we’ll need a different approach (or a polyfill).
2. It’s possible to «escape» from CSS/JS
function setIframeContent(iframe, html, css, js >) const source = ` $css> $html> $js>