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.

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 url = 'page.html';
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);

The following three functions incorporate these approaches:

function setIframeSrc(id, url) {
    document.getElementById(id).src = url;
}

function setIframeLoc(nm, url) {
    window.frames[nm].location = url;
}

function replaceIframeURL(nm, url) {
    window.frames[nm].location.replace(url);
}

Links in and to Iframed Documents

As mentioned above, links in the containing document intended for loading new documents into iframes can 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.

Back to top