Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture click event from child frame into parent frame

Right, this is weird. I have done loads of Googling and found hundreds of articles which seem to point me in the right direction, but none seem to work.

Here's the latest incarnation of what I am trying to do:

Parent Page

<html>
<head>
    <script>
    $('#mainWindow').ready(function () {
       $('#mainWindow').contents().find('#clickThis').live('click', function () {
           alert('Click detected!');
        });
    });
    </script>
</head>
<body>
    <iframe id="mainWindow" name="mainWindow" src="myMainPage.aspx" style="border: 0; position:fixed; top:0; left:0; right:0; bottom:0; width:100%; height:100%"></iframe>
    <iframe src="myOtherPage.aspx"></iframe>
</body>
</html>

Framed Page (sitting in mainWindow)

<html>
    ' LOADS OF STUFF INCLUDING:
    <li id="clickThis">Click This</li>
</html>

So obviously what I am trying to do here is to run some code in the Parent Page when a user clicks the button in the child frame.

It needs to work live so if the page in the frame changes it is still captured by the parent (this element exists on all pages which will be loaded into the frame)

I have been able to run codes across iFrames, from parent to iFrame and from iFrame to iFrame following various other searches, but running from iFrame to parent is causing issues.

The above code does nothing, and neither do any of the other options I have tried!!

*Edit should add, all files are on the same server, the cross domain issue is not a problem

like image 943
Jamie Hartnoll Avatar asked Jul 10 '12 12:07

Jamie Hartnoll


1 Answers

This works fine for me:

$('#myframe').contents().on('click', function () {
    $('#result').text('clicked');
});​

If you want to capture the events just on a part of the content document, use .contents().find(<selector>) (<selector> being e.g. 'body') instead of just .contents()

Something to watch out for: All of your pages must exist under the same document.domain or the JavaScript calls will fail. You will see this surfaced as a security exception in your console. This happens due to same-origin policy.

like image 195
jbabey Avatar answered Sep 30 '22 04:09

jbabey