开发者

Dynamic Script in IFrame not triggering window.onload

开发者 https://www.devze.com 2023-02-05 21:36 出处:网络
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.

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.


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();
0

精彩评论

暂无评论...
验证码 换一张
取 消