Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Javascript function defined inside iframe [duplicate]

I want to call javascript function (on click()) which is inside Iframe

<a onclick="abc();" href=# >Call Function which is inside Iframe </a>

<iframe id=myFrame>
   <script>
     function abc(){
         alert("I am inside Iframe");
     }
    </script>
</iframe>

It will be better if there is solution in JQuery.

Thank you

like image 582
Oomph Fortuity Avatar asked Mar 03 '14 13:03

Oomph Fortuity


People also ask

How do you call an iframe function?

document. getElementById("resultFrame") will get the iframe in your code, and contentWindow will get the window object in the iframe. Once you have the child window, you can refer to javascript in that context.

Are iframes considered bad practice?

Iframes Bring Security Risks. If you create an iframe, your site becomes vulnerable to cross-site attacks. You may get a submittable malicious web form, phishing your users' personal data. A malicious user can run a plug-in.

Can I get element inside iframe?

To get the element in an iframe, first we need access the <iframe> element inside the JavaScript using the document. getElementById() method by passing iframe id as an argument. const iframe = document.


2 Answers

You can do that this way:

<a onclick="$('#myFrame')[0].contentWindow.abc();">Call function which is inside of Iframe</a>

Basically, I get a reference to the Iframe. contentWindow is the global (window) object for the iframe, and all global functions in a document are methods of window.

As a note, you can only do this if both pages, the one containing the iframe and the one in the iframe come from the same domain.

like image 163
Oscar Paz Avatar answered Sep 20 '22 15:09

Oscar Paz


Use this to access your frame function:

    document.getElementById('myFrame').contentWindow.abc()
like image 41
radia Avatar answered Sep 19 '22 15:09

radia