3

I am dynamically creating an iframe with javascript inside the body.

iframe = m_oYDOM.get("ifAdwords");

iframe.contentWindow.document.body.innerHTML = <script type=\"text/javascript\">function Test(){alert(\"Success\");Test();}</script>";

I am not able to get the alert to work. Can someone help me!

Srikar Appalaraju
  • 71,928
  • 54
  • 216
  • 264
kishore
  • 719
  • 9
  • 29
  • 1
    see this question: http://stackoverflow.com/questions/251420/invoking-javascript-in-iframe-from-parent-page – bimbom22 Jul 20 '10 at 20:06
  • The above link is about calling a function from the parent page. But I want the function to be executed on iframe load – kishore Jul 20 '10 at 20:17

3 Answers3

2

I got this working

iframe = document.getElementByID("iFrameID");
var oDoc = iframe.contentWindow.document;
oDoc.open();
oDoc.write('<html><body><script type=\"text/javascript\">function Test(){alert(\"success\");}Test();<\/script><\/body><\/html>');
oDoc.close();
kishore
  • 719
  • 9
  • 29
0

Heres an example using jQuery that I use to execute javascript when a frame has loaded, I use it when redirecting the user to download a zip file, to control the browser after the download dialog appears.

Add a div to the page that will hold the iframe:

    <div style='height: 1px; width: 1px; border: 0;' id='iframediv'></div>

Then call the following to create the iframe with the onload action:

     var url = "http://google.com"
     $('#iframediv').html('<IFRAME id="downloadAlbum" onload="loadFunction()" src="'+url+'"></iframe>');

Change url and loadFunction as required.

A.Badger
  • 4,279
  • 1
  • 26
  • 18
0

.innerHTML is only for text changes... Call the script from another *.html file. OR just add onload to the end of iframe like so:

<iframe src="test.html" onload="alert('Success')";>
David
  • 13,619
  • 15
  • 45
  • 51