[Solved-5 Solutions] Invoking javascript code in an iframe from the parent page - javascript tutorial




Problem:

How to invoke JavaScript code in an iframe from the parent page ?

Solution 1:

Assume our iFrame's id is "targetFrame" and the function we want to call is targetFunction():

document.getElementById('targetFrame').contentWindow.targetFunction();

We can also access the frame using window.frames instead of document.getElementById.

window.frames[0].frameElement.contentWindow.targetFunction(); 

This option does not work in most of latest versions of chrome and Firefox

Solution 2:

  • HTMLIFrameElement.contentWindow is 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.

Solution 3:

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://.

Solution 4:

In the IFRAME, make our function public to the window object:

window.myFunction = function(args) {
   doStuff();
}

For access from the parent page, you can use this code:

var iframe = document.getElementById("iframeId");
iframe.contentWindow.myFunction(args);

Solution 5:

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 :

document
  .getElementById('targetFrame')
  .contentDocument
  .defaultView
  .targetFunction();


Related Searches to Invoking javascript code in an iframe from the parent page - javascript tutorial