views:

146

answers:

2

I have an HTML + javascript page that embeds a page in an iframe. I would like to be able to trigger a submit button (which causes a POST) within the embedded page using javascript in the enclosing page. Is there a library already doing this?

+6  A: 

If the IFRAME hosts a page in the same domain, you can say

// To trigger from the enclosing page
var yourFrame = document.getElementById("iframeId");
if(yourFrame.contentDocument) {    
   yourFrame.contentDocument.getElementById("formId").submit(); // FF, etc
} else {
   yourFrame.contentWindow.document.getElementById("formId").submit(); // IE
}

// To trigger from the enclosed page
document.getElementById("formId").submit();

... where iframeId is the ID of the iframe, and formId is the ID of the form inside the iframe, something like

Inside the document:

<iframe id="iframeId" src="/somePage.html" ... >

Inside the document at "somePage.html":

<form id="formId" method="post" action="...">

Note that if the IFRAME is hosting a page in another domain, then if you try to submit from the enclosing page, you will probably get some kind of "access denied" error. This is a security precaution taken by the browser to prevent malicious scripting (e.g. to prevent things like automatically submitting a form on a user's behalf)

Daniel LeCheminant
yourFrame.contentWindow.document only works in IE
geowa4
@George: You're absolutely correct; thanks for catching that!
Daniel LeCheminant
+1  A: 

The iframe needs to be in the same domain, otherwise you are SOL.

To access the elements in the frame, you need to behave differently in different browsers.

First, get the frame:

  • document.getElementById always works.
  • window.frames[ frameName ] should be fine too, but use the first one

Then get the document (here's where it gets tricky):

var doc = yourFrame.contentDocument ? yourFrame.contentDocument : yourFrame.contentWindow.document

Standards browsers require the use of contentDocument; IE (at least before 8) uses contentWindow.document to get the document.

Finally, you can grab the form and submit it.

doc.getElementById('yourForm').submit()
geowa4
+1 for proper using contentDocument
Daniel LeCheminant
being X-Browser is always handy
geowa4