Calling the Javascript function from the parent file from within an iframe

7

I have 2 files:

  • index.html
  • iframe.html

The file index.html has an iframe ( iframe.html ).

There is a javascript function in the file index.html

function testePai(){
    console.log("teste da função");
}

How do I call this function testePai() from javascript in iframe.html ?

    
asked by anonymous 07.05.2014 / 19:21

2 answers

10
  

Note:
  There is a protection called CORS that prevents opening content from a site within iFrame if the server does not allow it. >   There is another rule called " same-origin policy " that prevents a script from one page from interacting with another page if they have the same domain.

If the rules I mentioned above do not prevent you from calling this function on the page index.html with code inside the iFrame like this:

window.parent.testePai();

If you need to do the opposite, using pure javascript:

var iframeEl= document.getElementById("myIframe"); // ou outro seletor
var iframeDoc = iframeEl.contentDocument || iframeEl.contentWindow.document;
var iframe= iframeDoc.window;

// para chamar a função
iframe.minhaFuncao();
    
07.05.2014 / 19:23
2

In order to call the methods, variables and objects of the parent page, you must use window.parent .

In this way you can use this as if you were on the page itself as follows:

window.parent.testePai();

I consider it a good practice to define a variable to be able to access parent in a more organized way, eg

var index = window.parent; // você pode usar o nome que lhe for mais agradável para esta variável
index.testePai();
    
07.05.2014 / 19:25