How do I inject new content into an iframe?

How can i inject new content into an iframe. I found this code but can't get it to work:
You can see the 404 and position problem on vivinow.com/boydtest2/ and the code is as follows:

[iframe src="http://vivinow.com/atravelsquire/#travelsquire" width="700px" height="600px" scrolling="yes"]

<div>
<p>this a paragraph
<script type="text/javascript">
var newIframe = document.createElement('iframe');
newIframe.width = '900';newIframe.height = '500';
newIframe.src = 'myIframeContent.html';
document.body.appendChild(newIframe);
</script>
with an iframe in it.</p>
</div>

<script type="text/javascript">
var myIframeContent = '<!DOCTYPE html>'
+ '<html><head><title>My dynamic document</head>'
+ '<body><p>Hello world</p></body></html>';
newIframe.contentWindow.document.open('text/html', 'replace');
newIframe.contentWindow.document.write(myContent);
newIframe.contentWindow.document.close();
</script>
Thanks,
Boyd

  • Alexander

    Hi @vivinow,

    The problem is, your code is appending the iframe to the document body. That means it's being added at the bottom. It will wait until it reaches the paragraph tag it's been enclosed in to execute this, but it's not going to place the new iframe in that paragraph.

    What you're trying to accomplish might be easier done with a plugin and a shortcode. Take a look at the answer I posted on your other thread.

    However, to answer this, and to make this code work, you could have the new frame appended like this:

    document.getElementByID('p1').appendChild(newIframe);

    In this case you would just need to give the paragraph an ID of "p1" Actually to be honest a paragraph isn't really the best choice. It would be better to use a div instead.

    Best regards

  • Fox Jones

    Well, you may already know this, but the simplest way to load content into an iFrame from outside the iFrame is to target the ID of the frame via a link.

    for example, if your iFrame has an ID of "myFrame", you would create a link and set the target attribute to target="myFrame". for example:

    <a href="http://myframecontent.com" target="myFrame">open in frame</a>
    
    <iframe id="myFrame"></iframe>

    in the example, clicking "open in frame" will open the linked address in your frame.

    as Alex said, you're appending, not replacing. so, now knowing that you need to address the ID of the existing frame, can you modify the code to replace the frame content by ID?

    and as yet another alternative, i always liked jQuery for stuff like this. for example, http://stackoverflow.com/questions/2930315/changing-iframe-source-with-jquery

    hope that helps or at least gives you some ideas. : )

    - fox

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.