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

Asked

Viewed 10,853 times

8

I have 2 files:

  • index.html
  • iframe.html

The archive 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 existing javascript in the file iframe.html?

2 answers

11

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

If the rules I mentioned above do not prevent you can call this function on the page index.html with code inside the iframe like this:

window.parent.testePai();

If you need to do otherwise, 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();
  • 1

    Good @Rgio, otherwise I had never really seen it work. A while ago I got into it, researched it but had not found a solution that worked well.

  • 1

    @Erloncharles yes, and using jQuery for example is alone: $('#myIframe')[0].contentWindow.minhaFuncao()

  • Okay... you used jQuery practically just replacing the query selector js, then continued with pure js. That would be a mixed solution then, hehe. Still a good.

2

To be able to call the methods, variables and objects of the parent page you need to use the window.parent.

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 the Parent in a more organized, example:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.