IFrame中的动态脚本不触发window.onload [英] Dynamic Script in IFrame not triggering window.onload

查看:573
本文介绍了IFrame中的动态脚本不触发window.onload的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我动态地创建一个 IFrame 然后添加一个脚本标签给它,加载,但它永远不会执行。

  $ stage.html(< iframe src ='javascript :;'id = '框架' >< / 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);

我假设 window onload 事件是在将代码添加到 IFrame 之前触发。无论如何确保它被称为?它也需要包含在 window.onload 中,因为它是基于JS的代码编辑器,所以iframe必须像浏览器窗口中那样反应。干杯。使用 window.write()。解决方案 / p>

  frame = document.createElement(iframe); 
frame.src =javascript :;;
document.body.appendChild(frame);

win = frame.contentWindow;
win.document.open();
win.document.write(html);
win.document.close();


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

这篇关于IFrame中的动态脚本不触发window.onload的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆