Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Invoking JavaScript code in an iframe from the parent page

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.
by

2 Answers

akshay1995
Assume your iFrame's id is "targetFrame" and the function you want to call is targetFunction():

document.getElementById('targetFrame').contentWindow.targetFunction();
You can also access the frame using window.frames instead of document.getElementById.

// this option does not work in most of latest versions of chrome and Firefox
window.frames[0].frameElement.contentWindow.targetFunction();
sandhya6gczb
Calling a parent JS function from iframe is possible, but only when both the parent and the page loaded in the iframe are from same domain i.e. abc.com, and both are using same protocol i.e. both are either on http:// or https://.

The call will fail in below-mentioned cases:

Parent page and the iframe page are from different domain.
They are using different protocols, one is on http:// and other is on https://.
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 iframes 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.

Login / Signup to Answer the Question.