Rouge
Rouge

Reputation: 4239

How to assign click event to elements inside iframe?

How to assign click event to elements inside ifraem?

I started a post to detect if the iframe is loaded.

How can I detect whether an iframe is loaded?

and I have further quesitons

How do I assign an event or manipulate elements inside the iframe??

I tried..

$(function(){
    $('#click').on('click', function(){
        var ifr=$('<iframe></iframe>', {
            id:'MainPopupIframe',
            src:'http://heera.it',
            style:'display:none',
            load:function(){
                $(this).show();
                alert('iframe loaded !');
            }
        });
        $('body').append(ifr);    

    //when I click the home page button, nothing happen...
    $('#menu-item-277').click(function(){
       alert('click!!!');
    })
    });
});
​

Thanks for the help.

Upvotes: 0

Views: 1952

Answers (2)

dSquared
dSquared

Reputation: 9825

Due to cross domain security restrictions (same origin policy) this is not possible if the iframe's content exists on a domain other than the parent page.

If you have access to both domains you can try using a plugin such as Ben Alman's excellent PostMessage to set-up a Cross-Domain / Cross-Browser iframe communication stream. You could then bind to the click event of a local DOM element and send a message to the iframe where a polling loop could listen for it and trigger the click event within the iframe.

I hope this helps.

Upvotes: 1

Charlie
Charlie

Reputation: 11777

You can't due to the same origin policy. Basically, the iframe has to be on the same domain as the script that's trying to modify it.

Upvotes: 0

Related Questions