Dynamic Script in IFrame not triggering window.onload

ⅰ亾dé卋堺 提交于 2020-02-08 02:59:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!