我动态创建一个 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 必须像在浏览器窗口中一样使用react。干杯。
最佳答案
通过使用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();
关于javascript - IFrame 中的动态脚本不触发 window.onload,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4743519/