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.

3
  • is the iframe from the same domain/protocol? Commented May 20, 2011 at 14:38
  • 3
    possible duplicate of Invoking javascript in iframe from parent page Commented May 20, 2011 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. Commented May 20, 2011 at 14:44

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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();
...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.