Trigger buttons in an iframe

I have an HTML + javascript page that includes a page in an iframe. I would like to be able to trigger a submit button (which triggers a POST) on an inline page using javascript on the attached page. Is there a library out there that already does this?

0


a source to share


2 answers


If IFRAME

hosts a page on 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 in the " somePage.html

" section :

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

      

Note that if you IFRAME

host a page on a different domain, then if you try to submit from the attached page, you are likely to get some sort of "access denied" error. This is a security warning issued by the browser to prevent malicious scripting (for example, to prevent cases such as automatic form submission on behalf of the user).

+7


a source


iframe

must be in the same domain, otherwise you are SOL.

In order to access elements in a frame, you need to behave differently in different browsers.

First take a frame:

  • document.getElementById

    always works.
  • window.frames[ frameName ]

    should be fine too, but use the first

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



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

      

Standard browsers require use contentDocument

; IE (up to at least 8) uses contentWindow.document

to get the document.

Finally, you can grab the form and submit it.

doc.getElementById('yourForm').submit()

      

+1


a source







All Articles