问题
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.
回答1:
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();
来源:https://stackoverflow.com/questions/4743519/dynamic-script-in-iframe-not-triggering-window-onload