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 opposite is quite simple as you only need to call parent.functionName()
, but unfortunately, I need exactly the opposite of that.
Please note that my problem is not changing the source URL of the iframe
, but invoking a function defined in the iframe
.
If We want call the parent page javascript function from the iframe which generated from the coding. ex shadowbox or lightbox
window.parent.targetFunction();
Calling a parent JS function from
iframe
is possible, but only when both the parent and the page loaded in theiframe
are from same domain i.e. abc.com, and both are using same protocol i.e. both are either onhttp://
orhttps://
.The call will fail in below mentioned cases:
Any workaround to this restriction would be extremely insecure.
For instance, imagine I registered the domain superwinningcontest.com and sent out links to people's emails. When they loaded up the main page, I could hide a few
iframe
s in there and read their Facebook feed, check recent Amazon or PayPal transactions, or--if they used a service that did not implement sufficient security--transfer money out of their accounts. That's why JavaScript is limited to same-domain and same-protocol.In the IFRAME, make your function public to the window object:
For access from the parent page, use this:
Assume your iFrame's id is "targetFrame" and the function you want to call is
targetFunction()
:You can also access the frame using
window.frames
instead ofdocument.getElementById
.Folowing Nitin Bansal's answer
and for even more robustness:
and
I found quite an elegant solution.
As you said, it's fairly easy to execute code located on the parent document. And that's the base of my code, do to just the opposite.
When my iframe loads, I call a function located on the parent document, passing as an argument a reference to a local function, located in the iframe's document. The parent document now has a direct access to the iframe's function thru this reference.
Example:
On the parent:
On the iframe:
When the iframe loads, it will call parent.tunnel(YourFunctionReference), which will execute the function received in parameter.
That simple, without having to deal with the all the non-standards methods from the various browsers.