Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling javascript function in iframe

I have problem calling a JavaScript function in an iframe from the parent page. Here is my two pages:

mainPage.html

<html> <head>     <title>MainPage</title>     <script type="text/javascript">         function Reset()          {             if (document.all.resultFrame)                 alert("resultFrame found");             else                 alert("resultFrame NOT found");              if (typeof (document.all.resultFrame.Reset) == "function")                 document.all.resultFrame.Reset();             else                 alert("resultFrame.Reset NOT found");         }     </script> </head> <body>     MainPage<br>     <input type="button" onclick="Reset()" value="Reset"><br><br>     <iframe height="100" id="resultFrame" src="resultFrame.html"></iframe> </body> </html> 

resultFrame.html

<html> <head>     <title>ResultPage</title>     <script type="text/javascript">         function Reset()          {             alert("reset (in resultframe)");         }     </script> </head> <body>     ResultPage </body> </html> 

(I know that document.all isn't recommended but this page should only be viewed with IE internally and I don't think that's the problem)

When I press the Reset-button I get "resultFrame found" and "resultFrame.Reset NOT found". It seems to have a reference to the frame but can't call the function on the frame, why is that?

like image 800
salle55 Avatar asked Oct 21 '09 12:10

salle55


People also ask

Can you run JavaScript in iframe?

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. example.com , and both are using same protocol i.e. both are either on http:// or https:// .

How do you call an iframe function?

To call JavaScript function in an iframe, we get the window object of the iframe with the contentWindow property. document. getElementById("resultFrame"). contentWindow.

How do you call a function after an iframe is loaded?

To call a JavaScript function when iframe finished loading, we can add an event listener for the load event. to add an iframe. to select the iframe with querySelector .

How do I select an iframe element?

Getting the element in Iframeconst iframe = document. getElementById("myIframe"); Now, it has and contentWindow property which returns the document object by using that we can access the elements from an Iframe. const iWindow = iframe.


1 Answers

Use:

document.getElementById("resultFrame").contentWindow.Reset(); 

to access the Reset function in the iframe

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.

Also see HERE in particular the answer from bobince.

like image 95
Jonathan Fingland Avatar answered Sep 19 '22 19:09

Jonathan Fingland