I want to load HTML as string into an iframe
via Javascript. like this:
$('#iframe1').contents().find('html').html("<h1>This is an iframe</h1>");
this worked great until I found out, that inside this HTML upcomming Javascript like document.write
are writing to the wrong document -> the parent!
Here is a Plunker to show it: http://plnkr.co/edit/YQAqqSDCVKnP3uhLj4lF?p=preview
if I load the same HTML to the iframe
via src as external document, the document.write
goes to the iframe
(and not to the parent), which is what i was expecting.
Are there some insights out there? How can I tell the browser to correctly create the iframes document scope before it executes its Javascript?
PS: Its meant to be for preview purposes, so i inject HTML-Code of a (trusted!) source, but within that code, document.write is allowed.
Ok. srcdoc
is helpfull here.
$('#iframe1').attr({srcdoc:intrusiveHTML});
I updated the Plunker.
With srcdoc
, Javascript won't slip up with the document scope.
It won't work in IE ( http://caniuse.com/#feat=iframe-srcdoc ), so it might help to use Polyfill additionally: https://github.com/jugglinmike/srcdoc-polyfill
But I did not test that yet.
Instead of using document.write
, use document.getElementById('iframe1').contentWindow.document.write
. Because when you point document it will take main window document, so we need to indicate which iframe doument need to be used.
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.