14

I don't have access to this iframe's source directly, so I would like to do this, if it's possibly this way.

I have an iframe generated by JS:

<iframe name="temp_iframe" width="100%" height="95%" src="'+the_url+'"></iframe>

And inside is a submit button and a cancel button. The submit button works fine, but I want the cancel button to close this modal that is containing the iframe... I also want the submit button to send, then close the modal. Normally this would be easy, but im not sure how to setup an event in the parent window to a child DOM element of the iframe that affects the child's parent, the main window.

E.g. if this wasn't in an iframe and in jQuery:

$('[name=temp_iframe] button').live('click',function(){
    alert('click');
    return false;
});

EDIT: And also, it's on the same domain!

Bob Stein
  • 16,271
  • 10
  • 88
  • 101
Oscar Godson
  • 31,662
  • 41
  • 121
  • 201
  • If the source of the iframe is another domain, you can't do that due to cross site scripting restrictions. – Peter Ajtai Sep 08 '10 at 23:41
  • its the same domain... i just don't have access. I work for City of Portland, OR, and i have to request changes to the server side code... – Oscar Godson Sep 08 '10 at 23:44
  • Suggest title change: **Attach an event in a child iframe to a handler in the parent window**. The current wording sounds as if you wanted to `.trigger()` an event in the child. This confusion lead to an erroneous duplicate-close-vote on [a question that does use trigger](https://stackoverflow.com/q/27332339/673991). – Bob Stein Jun 02 '17 at 15:32

2 Answers2

14

Use contents() to access the Document object inside an iframe. Note that there are in general problems with using a jQuery library in one document to manipulate another document and it should in general be avoided. However, in the case of binding events it does work.

$('[name=temp_iframe]').contents().find('button').click(function() {
    alert('click');
});

This requires that the iframe and its contents are loaded, so do it in a $(window).load() handler if necessary. You can't live/delegate across documents, as events don't propagate from a child document into its parent.

bobince
  • 528,062
  • 107
  • 651
  • 834
3

In plain JavaScript it would be:

document.getElementById("frameId").contentDocument.getElementById("buttonId").click();

If you need to search elements by attribute value and tag name, you can:

document.querySelectorAll('[name=temp_iframe]')[0].contentDocument.getElementsByTagName('button')[0].click();
mjaque
  • 472
  • 5
  • 10