Loading New Documents into Iframes

This part of the Iframes Tutorial provides information on loading new documents into iframes using either JavaScript or link target attributes. An example demonstrates.

JavaScript isn't necessary when you want clicking on a link to change the src of an iframe since links can specify an iframe in their target attribute. A link set up as follows will load page.html into an iframe with name ifrm:

<a href="page.html" target="ifrm">link</a>

Nonetheless, there may be situations where you will want to use JavaScript to change the URL in an iframe.

JavaScript to Change the URL in an Iframe

There are three ways to load a new document into an iframe using JavaScript. The first method uses document.getElementById to reference the iframe element and assigns a new URL to its src property:

var el = document.getElementById('ifrm');
el.src = url; // assign url to src property

A second alternative uses the frames array to obtain a reference to the iframe window and assigns the new URL to its location property:

window.frames['ifrm'].location = url;

A third alternative uses the location.replace method in order to avoid having the new URL added to the browser history:

window.frames['ifrm'].location.replace(url);

An example demonstrates all three approaches.

Links in and to Iframed Documents

As mentioned above, links in the containing document intended for loading new documents into iframes indicate that by including the name of the iframe in their target attribute.

Links in the document inside the iframe will by default load new documents inside the iframe. If you want a link in the iframed document to load a URL in the main window, include a target attribute set to _parent:

<a href="page.html" target="_parent">link</a>

Loading Documents from Other Domains into Iframes

It is generally possible to load documents from other domains in iframes. However, it would not be possible for the containing document to make a reference to the document inside the iframe due to the restrictions of the Same Origin Policy. Also, the page from the other domain could contain code that would prevent its being loaded in your iframe.

Demonstration, Download, and More

An example demonstrates the concepts presented here. See also how you can use query string data to specify which document to load in an iframe. The Iframes Tutorial includes much more information on iframes and how they are used. The tutorial examples are all included in a download file.