Attach an event in a child iframe to a handler in the parent window

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!

Answers:

Answer

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.

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.