Basically, I have an iframe
embedded in a page and the iframe
has some JavaScript routines I need to invoke from the parent page.
Now the o
In the IFRAME, make your function public to the window object:
window.myFunction = function(args) {
doStuff();
}
For access from the parent page, use this:
var iframe = document.getElementById("iframeId");
iframe.contentWindow.myFunction(args);
Some of these answers don't address the CORS issue, or don't make it obvious where you place the code snippets to make the communication possible.
Here is a concrete example. Say I want to click a button on the parent page, and have that do something inside the iframe. Here is how I would do it.
parent_frame.html
<button id='parent_page_button' onclick='call_button_inside_frame()'></button>
function call_button_inside_frame() {
document.getElementById('my_iframe').contentWindow.postMessage('foo','*');
}
iframe_page.html
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event)
{
if(event) {
click_button_inside_frame();
}
}
function click_button_inside_frame() {
document.getElementById('frame_button').click();
}
To go the other direction (click button inside iframe to call method outside iframe) just switch where the code snippet live, and change this:
document.getElementById('my_iframe').contentWindow.postMessage('foo','*');
to this:
window.parent.postMessage('foo','*')
If you want to invoke the JavaScript function on the Parent from the iframe generated by another function ex shadowbox or lightbox.
You should try to make use of window
object and invoke parent function:
window.parent.targetFunction();
Same things but a bit easier way will be How to refresh parent page from page within iframe. Just call the parent page's function to invoke javascript function to reload the page:
window.location.reload();
Or do this directly from the page in iframe:
window.parent.location.reload();
Both works.
Continuing with JoelAnair's answer:
For more robustness, use as follows:
var el = document.getElementById('targetFrame');
if(el.contentWindow)
{
el.contentWindow.targetFunction();
}
else if(el.contentDocument)
{
el.contentDocument.targetFunction();
}
Workd like charm :)
$("#myframe").load(function() {
alert("loaded");
});