Search code examples
javascripthtmliframeonload-event

Dynamic Script in IFrame not triggering window.onload


I am dynamically creating an IFrame then adding a script tag to it with code that should execute when the frame loads, however it is never executed.

$stage.html("<iframe src='javascript:;' id='frame'></iframe>");
$frame = $("#frame");

frame =  $frame[0].contentDocument ? $frame[0].contentDocument :  $frame[0].contentWindow.document;

script= frame.createElement('script'),
head = frame.getElementsByTagName("head")[0];

script.innerHTML = "window.onload = function() { alert('loaded'); }";

head.appendChild(script);

I am assuming the window onload event is triggered before the code is added to the IFrame. Is there anyway to ensure it is called? Also it needs to be contained with in window.onload as it is for a JS based code editor so the iframe has to react as it would in a browser window. Cheers.


Solution

  • Solved by using window.write().

    frame = document.createElement("iframe"); 
    frame.src = "javascript:;";
    document.body.appendChild(frame);
    
    win = frame.contentWindow;
    win.document.open();
    win.document.write(html);
    win.document.close();