0

Good day to all.

I have the following setup:

A page with html, js, etc. (usual stuff) and an iFrame. In the iFrame I have a function that do something (anything.. alert('test'); for example).

I need to run that function if I click on a button on the main page.

For example if I push button alert in the main page, in the iFrame must appear an alert with the 'test' word.

James Wiseman
  • 29,946
  • 17
  • 95
  • 158
zozo
  • 8,230
  • 19
  • 79
  • 134
  • is the iframe from the same domain/protocol? – Matt May 20 '11 at 14:38
  • 3
    possible duplicate of [Invoking javascript in iframe from parent page](http://stackoverflow.com/questions/251420/invoking-javascript-in-iframe-from-parent-page) – RaYell May 20 '11 at 14:39
  • @Matt yes, @RaYell: Yes it is almost duplicate. My bad I didn't see it. Here's a +1 for your time. – zozo May 20 '11 at 14:44

2 Answers2

2

document.frames[n] make frames accessible by the order they appear in the document. so document.frames[0].contentWindow.myFunction() would call your function inside the frame in case the iframe is the only frame.

Calling a function in the main window from the frame works via top like top.myFunction(). If you just want to go one level up you use parent.

Cobra_Fast
  • 15,671
  • 8
  • 57
  • 102
0

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');

getIframeWindow(el).targetFunction();
...
Dominique Fortin
  • 2,212
  • 15
  • 20