繁体   English   中英

IFrame中的动态脚本不会触发window.onload

[英]Dynamic Script in IFrame not triggering window.onload

我正在动态创建一个IFrame然后向其添加一个script标记,其中包含应在加载框架时执行的代码,但是它从不执行。

$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);

我假设在将代码添加到IFrame之前触发了window onload事件。 无论如何,有没有确保它被调用? 同样,它也需要包含在window.onload就像基于JS的代码编辑器一样,因此iframe必须像在浏览器窗口中那样做出反应。 干杯。

通过使用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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM