642
votes

Basically, I have an iframe embedded in a page and the iframe has some JavaScript routines I need to invoke from the parent page.

Now the opposite is quite simple as you only need to call parent.functionName(), but unfortunately, I need exactly the opposite of that.

Please note that my problem is not changing the source URL of the iframe, but invoking a function defined in the iframe.

17
Note when debugging you can do things like window.location.href or parent.location.href to view the url of the iframe, if you want to verify that you have a reference to the iframe you are looking for.AaronLS

17 Answers

570
votes

Assume your iFrame's id is "targetFrame" and the function you want to call is targetFunction():

document.getElementById('targetFrame').contentWindow.targetFunction();

You can also access the frame using window.frames instead of document.getElementById.

// this option does not work in most of latest versions of chrome and Firefox
window.frames[0].frameElement.contentWindow.targetFunction(); 
153
votes

There are some quirks to be aware of here.

  1. HTMLIFrameElement.contentWindow is probably the easier way, but it's not quite a standard property and some browsers don't support it, mostly older ones. This is because the DOM Level 1 HTML standard has nothing to say about the window object.

  2. You can also try HTMLIFrameElement.contentDocument.defaultView, which a couple of older browsers allow but IE doesn't. Even so, the standard doesn't explicitly say that you get the window object back, for the same reason as (1), but you can pick up a few extra browser versions here if you care.

  3. window.frames['name'] returning the window is the oldest and hence most reliable interface. But you then have to use a name="..." attribute to be able to get a frame by name, which is slightly ugly/deprecated/transitional. (id="..." would be better but IE doesn't like that.)

  4. window.frames[number] is also very reliable, but knowing the right index is the trick. You can get away with this eg. if you know you only have the one iframe on the page.

  5. It is entirely possible the child iframe hasn't loaded yet, or something else went wrong to make it inaccessible. You may find it easier to reverse the flow of communications: that is, have the child iframe notify its window.parent script when it has finished loaded and is ready to be called back. By passing one of its own objects (eg. a callback function) to the parent script, that parent can then communicate directly with the script in the iframe without having to worry about what HTMLIFrameElement it is associated with.

69
votes

Calling a parent JS function from iframe is possible, but only when both the parent and the page loaded in the iframe are from same domain i.e. abc.com, and both are using same protocol i.e. both are either on http:// or https://.

The call will fail in below mentioned cases:

  1. Parent page and the iframe page are from different domain.
  2. They are using different protocols, one is on http:// and other is on https://.

Any workaround to this restriction would be extremely insecure.

For instance, imagine I registered the domain superwinningcontest.com and sent out links to people's emails. When they loaded up the main page, I could hide a few iframes in there and read their Facebook feed, check recent Amazon or PayPal transactions, or--if they used a service that did not implement sufficient security--transfer money out of their accounts. That's why JavaScript is limited to same-domain and same-protocol.

36
votes

In the IFRAME, make your function public to the window object:

window.myFunction = function(args) {
   doStuff();
}

For access from the parent page, use this:

var iframe = document.getElementById("iframeId");
iframe.contentWindow.myFunction(args);
23
votes

If the iFrame's target and the containing document are on a different domain, the methods previously posted might not work, but there is a solution:

For example, if document A contains an iframe element that contains document B, and script in document A calls postMessage() on the Window object of document B, then a message event will be fired on that object, marked as originating from the Window of document A. The script in document A might look like:

var o = document.getElementsByTagName('iframe')[0];
o.contentWindow.postMessage('Hello world', 'http://b.example.org/');

To register an event handler for incoming events, the script would use addEventListener() (or similar mechanisms). For example, the script in document B might look like:

window.addEventListener('message', receiver, false);
function receiver(e) {
  if (e.origin == 'http://example.com') {
    if (e.data == 'Hello world') {
      e.source.postMessage('Hello', e.origin);
    } else {
      alert(e.data);
    }
  }
}

This script first checks the domain is the expected domain, and then looks at the message, which it either displays to the user, or responds to by sending a message back to the document which sent the message in the first place.

via http://dev.w3.org/html5/postmsg/#web-messaging

9
votes

Just for the record, I've ran into the same issue today but this time the page was embedded in an object, not an iframe (since it was an XHTML 1.1 document). Here's how it works with objects:

document
  .getElementById('targetFrame')
  .contentDocument
  .defaultView
  .targetFunction();

(sorry for the ugly line breaks, didn't fit in a single line)

9
votes

Some of these answers don't address the CORS issue, or don't make it obvious where you place the code snippets to make the communication possible.

Here is a concrete example. Say I want to click a button on the parent page, and have that do something inside the iframe. Here is how I would do it.

parent_frame.html

<button id='parent_page_button' onclick='call_button_inside_frame()'></button>

function call_button_inside_frame() {
   document.getElementById('my_iframe').contentWindow.postMessage('foo','*');
}

iframe_page.html

window.addEventListener("message", receiveMessage, false);

function receiveMessage(event)
    {
      if(event) {
        click_button_inside_frame();
    }
}

function click_button_inside_frame() {
   document.getElementById('frame_button').click();
}

To go the other direction (click button inside iframe to call method outside iframe) just switch where the code snippet live, and change this:

document.getElementById('my_iframe').contentWindow.postMessage('foo','*');

to this:

window.parent.postMessage('foo','*')
8
votes

The IFRAME should be in the frames[] collection. Use something like

frames['iframeid'].method();
8
votes

Quirksmode had a post on this.

Since the page is now broken, and only accessible via archive.org, I reproduced it here:

IFrames

On this page I give a short overview of accessing iframes from the page they’re on. Not surprisingly, there are some browser considerations.

An iframe is an inline frame, a frame that, while containing a completely separate page with its own URL, is nonetheless placed inside another HTML page. This gives very nice possibilities in web design. The problem is to access the iframe, for instance to load a new page into it. This page explains how to do it.

Frame or object?

The fundamental question is whether the iframe is seen as a frame or as an object.

  • As explained on the Introduction to frames pages, if you use frames the browser creates a frame hierarchy for you (top.frames[1].frames[2] and such). Does the iframe fit into this frame hierarchy?
  • Or does the browser see an iframe as just another object, an object that happens to have a src property? In that case we have to use a standard DOM call (like document.getElementById('theiframe')) to access it. In general browsers allow both views on 'real' (hard-coded) iframes, but generated iframes cannot be accessed as frames.

NAME attribute

The most important rule is to give any iframe you create a name attribute, even if you also use an id.

<iframe src="iframe_page1.html"
    id="testiframe"
    name="testiframe"></iframe>

Most browsers need the name attribute to make the iframe part of the frame hierarchy. Some browsers (notably Mozilla) need the id to make the iframe accessible as an object. By assigning both attributes to the iframe you keep your options open. But name is far more important than id.

Access

Either you access the iframe as an object and change its src or you access the iframe as a frame and change its location.href.

document.getElementById('iframe_id').src = 'newpage.html'; frames['iframe_name'].location.href = 'newpage.html'; The frame syntax is slightly preferable because Opera 6 supports it but not the object syntax.

Accessing the iframe

So for a complete cross–browser experience you should give the iframe a name and use the

frames['testiframe'].location.href

syntax. As far as I know this always works.

Accessing the document

Accessing the document inside the iframe is quite simple, provided you use the name attribute. To count the number of links in the document in the iframe, do frames['testiframe'].document.links.length.

Generated iframes

When you generate an iframe through the W3C DOM the iframe is not immediately entered into the frames array, though, and the frames['testiframe'].location.href syntax will not work right away. The browser needs a little time before the iframe turns up in the array, time during which no script may run.

The document.getElementById('testiframe').src syntax works fine in all circumstances.

The target attribute of a link doesn't work either with generated iframes, except in Opera, even though I gave my generated iframe both a name and an id.

The lack of target support means that you must use JavaScript to change the content of a generated iframe, but since you need JavaScript anyway to generate it in the first place, I don't see this as much of a problem.

Text size in iframes

A curious Explorer 6 only bug:

When you change the text size through the View menu, text sizes in iframes are correctly changed. However, this browser does not change the line breaks in the original text, so that part of the text may become invisible, or line breaks may occur while the line could still hold another word.

7
votes

I found quite an elegant solution.

As you said, it's fairly easy to execute code located on the parent document. And that's the base of my code, do to just the opposite.

When my iframe loads, I call a function located on the parent document, passing as an argument a reference to a local function, located in the iframe's document. The parent document now has a direct access to the iframe's function thru this reference.

Example:

On the parent:

function tunnel(fn) {
    fn();
}

On the iframe:

var myFunction = function() {
    alert("This work!");
}

parent.tunnel(myFunction);

When the iframe loads, it will call parent.tunnel(YourFunctionReference), which will execute the function received in parameter.

That simple, without having to deal with the all the non-standards methods from the various browsers.

4
votes

Continuing with JoelAnair's answer:

For more robustness, use as follows:

var el = document.getElementById('targetFrame');

if(el.contentWindow)
{
   el.contentWindow.targetFunction();
}
else if(el.contentDocument)
{
   el.contentDocument.targetFunction();
}

Workd like charm :)

3
votes

Folowing Nitin Bansal's answer

and for even more robustness:

function getIframeWindow(iframe_object) {
  var doc;

  if (iframe_object.contentWindow) {
    return iframe_object.contentWindow;
  }

  if (iframe_object.window) {
    return iframe_object.window;
  } 

  if (!doc && iframe_object.contentDocument) {
    doc = iframe_object.contentDocument;
  } 

  if (!doc && iframe_object.document) {
    doc = iframe_object.document;
  }

  if (doc && doc.defaultView) {
   return doc.defaultView;
  }

  if (doc && doc.parentWindow) {
    return doc.parentWindow;
  }

  return undefined;
}

and

...
var el = document.getElementById('targetFrame');

var frame_win = getIframeWindow(el);

if (frame_win) {
  frame_win.targetFunction();
  ...
}
...
2
votes
       $("#myframe").load(function() {
            alert("loaded");
        });
2
votes

Same things but a bit easier way will be How to refresh parent page from page within iframe. Just call the parent page's function to invoke javascript function to reload the page:

window.location.reload();

Or do this directly from the page in iframe:

window.parent.location.reload();

Both works.

2
votes

If you want to invoke the JavaScript function on the Parent from the iframe generated by another function ex shadowbox or lightbox.

You should try to make use of window object and invoke parent function:

window.parent.targetFunction();
1
votes

Try just parent.myfunction()

-3
votes

Use following to call function of a frame in parent page

parent.document.getElementById('frameid').contentWindow.somefunction()