March 3, 2012

Target buttons in an iframe?

Question by pufAmuf

I’m doing an Android Web catalog, and for that reason I had to use iframes. I wanted to ask, however, is it possible to click a button in an iframe and make the code work in the main page?

This is the code I have:

     function initFastButtons() {
        new FastButton(document.getElementById("CloseButton"), runclose);
        new FastButton(document.getElementById("OpenButton"), runopen);
     };
     function runclose() {
        $('.full-preview-viewer').hide();
     };
     function runopen() {
        $('.full-preview-viewer').show();
     };

And this is what a button in an iframe looks like:

<input id="OpenButton" type="image" src="products/special/product1.png" name="image" width="336" height="593"></input>

Thanks everyone 🙂

Answer by Jason Bury

You can move the definitions for “runclose()” and “runopen()” to your parent window (the document that is creating the iframe). Then, in your iframe you can modify your initFastButtons() setup to reference those functions as “parent.runclose” and “parent.runopen”. Note that normally this sort of thing is limited when the pages are not requested from the same domain.

Consider these two pages, “inner.html” and “outer.html”:

outer.html:

<html>
<head>
<script type="text/javascript">
window.do_action = function () {
    alert('the button was clicked!');
}
</script>
</head>
<body>
    <iframe src="inner.html"></iframe>
</body>
</html>

inner.html:

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
    $('button').click(parent.do_action);
});
</script>
</head>
<body>
    <button>Click Me!</button>
</body>
</html>

Answer by Starx

You can click a button inside an iframe using the following technique.

var $currentIFrame = $('#IFrameId');
$currentIFrame.contents().find("#OpenButton").trigger("click");

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!