Jim
Jim

Reputation: 1161

Triggering buttons in contained iframe

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?

Upvotes: 0

Views: 1778

Answers (2)

Daniel LeCheminant
Daniel LeCheminant

Reputation: 51081

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)

Upvotes: 7

geowa4
geowa4

Reputation: 41823

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

Upvotes: 1

Related Questions