Assume our iFrame's id is "targetFrame" and the function we want to call is targetFunction():
We 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
HTMLIFrameElement.contentWindowis the easier way, but it's not quite a standard property and some browsers don't support it. This is because the DOM Level 1 HTML standard has nothing to say about the window object.
- We can also try
HTMLIFrameElementcontentDocument.defaultView, which allows earlier version of browsers but IE doesn't support.
window.frames['name']returning the window is the oldest and hence most reliable interface. But we have to use a
name="..."attribute to be able to get a frame by name, which is slightly transitional.
window.frames[number]is also very reliable.
- It is entirely possible the child iframe hasn't loaded yet, or something else went wrong to make it unreachable. We may find it easier to reverse the flow of communications that is, have the child iframe notify its window.parent script when it has finished loaded and is ready to be called back. By passing one of its own objects (e.g. a callback function) to the parent script, that parent can then communicate directly with the script in the iframe without having to concern about what HTMLIFrameElement it is related with.
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. xxx.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://.
Read AlsoBest way to find an item in java script
In the IFRAME, make our function public to the window object:
For access from the parent page, you can use this code:
The page was embedded in an object, not an iframe (since it was an XHTML 1.1 document). Here's how it works with objects :