- 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?
- Общение между окнами и фреймами
- Переход внутрь ифрейма
- Кросс-доменность: ограничение доступа к окну
- Иерархия window.frames
- Песочница sandbox
- JavaScript write to IFrame
- Write to IFrame using JavaScript
- Tutorials
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>