Answer: Use the jQuery contents() method You can use the jQuery contents() method in combination with the find() , val() and html() methods to insert text or HTML inside an iframe body.
Iframes are most often used to embed specific content from one web page — like a video, form, document, or even a full web page — within a different web page. This is a powerful capability in HTML — you can take any content from any website (with permission) and place it on your own site to enhance your content.
Approach 1: For adding additional div's in an iframe, you need to use a wrapper div, that wraps the contents of your intended div and the iframe into one unit. This way you can display the contents of your div along with the iframe embedding to the document/webpage.
If it is a static HTML site, create a new page with the content which you want to show and set the src of the <iframe> . If it is a dynamic page app (server side), create a new page or handler or controller (whatever applies) and set the src of the <iframe> .
You really don't need jQuery for that:
var doc = document.getElementById('iframe').contentWindow.document;
doc.open();
doc.write('Test');
doc.close();
jsFiddle Demo
If you absolutely have to use jQuery, you should use contents()
:
var $iframe = $('#iframe');
$iframe.ready(function() {
$iframe.contents().find("body").append('Test');
});
jsFiddle Demo
Please don't forget that if you're using jQuery, you'll need to hook into the DOMReady function as follows:
$(function() {
var $iframe = $('#iframe');
$iframe.ready(function() {
$iframe.contents().find("body").append('Test');
});
});
This should do what you want:
$("#iframe").ready(function() {
var body = $("#iframe").contents().find("body");
body.append('Test');
});
Check this JSFiddle for working demo.
Edit: You can of course do it one line style:
$("#iframe").contents().find("body").append('Test');
You can enter (for example) text from div into iFrame:
var $iframe = $('#iframe');
$iframe.ready(function() {
$iframe.contents().find("body").append($('#mytext'));
});
and divs:
<iframe id="iframe"></iframe>
<div id="mytext">Hello!</div>
and JSFiddle demo: link
Wait, are you really needing to render it using javascript?
Be aware that in HTML5 there is srcdoc
, which can do that for you! (The drawback is that IE/EDGE does not support it yet https://caniuse.com/#feat=iframe-srcdoc)
See here [srcdoc
]: https://www.w3schools.com/tags/att_iframe_srcdoc.asp
Another thing to note is that if you want to avoid the interference of the js code inside and outside you should consider using the sandbox
mode.
See here [sandbox
]: https://www.w3schools.com/tags/att_iframe_sandbox.asp
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With