If possible, can I click on an element in an iframe and have that perform a function on the page it is rendered on?
for example:
<div class="page">
<iframe class="frame">[... the source will render: <div class="clickme"></div>...]
</iframe>
...meanwhile, back on the main page...
<script>
$(".clickme").click(function(){
alert('clicked');
});
</script>
</div>
edit also, I forgot to mention that the iframe's src changes after the page loads, this could be an obstacle!
It doesn't seem to work for me and I couldn't find an appropriate answer/question here. Thanks!
If the user clicking on an item in the iframe should result in a function firing in the parent, then the following will work, assuming you have a function called doStuff
in the parent:
window.top.doStuff();
Of course, this requires the domain of the iframe to match the domain of the parent page.
What if it needs to be cross-domain?
If you require cross-domain communication, then the HTML5 postMessage function will empower you to register the parent page as a listener to the iframe, allowing the iframe to pass messages to the parent page.
In the parent HTML, register a listener:
// register to listen for postMessage events
window.addEventListener("message", receiveMessage, false);
// this is the callback handler to process the event
function receiveMessage(event)
{
// you're responsible for your own security. Make sure requests are
// coming from domains you whitelist!
if (event.origin !== "http://example.org:8080")
return;
if(event.data == "click!") {
// do your stuff on the parent page here
}
}
In the iframe HTML page:
// pass the string "click!" to the parent page, where the receiveMessage
// handler will take action when it sees the message matches.
top.window.postMessage("click!", targetOrigin);
See window.postMessage for more details.
You can access element in iframe using content()
$('.frame').contents().find('.clickme').each(function(){
$(this).click(function(){ //this is .clickme
//enter code here
})
});
note if iframe's src come from different domain you 'll get access denied.
you can call a function in the Iframe,
window.frames['iframeName'].yourFunction();
and in the Iframe
<script>
$(".clickme").click(function(){
yourFunction();
});
function yourFunction(){
alert('clicked');
}
</script>