强制iframe评估其javascript

Force iframe to evaluate its javascript?

本文关键字:javascript 评估 iframe 强制      更新时间:2023-09-26

我正在动态创建一个iframe,在某个时候我需要将javascript插入其中。我可以添加带有字符串的标记,但有没有办法强制iframe重新评估其脚本,以便javascript可执行?

需要做什么的简单例子是,用户提供:

<h2 onclick="doSomething();">Click me</h2>

function doSomething() { alert('you clicked me'); }

我需要将html推送到iframe的主体中,并且我需要将javascript字符串推送到ifame的脚本中,使其能够工作。

HTML

<!--Container of iframe, iframe will be appended to this div later-->
​<div id='myDiv'>​</div>​ 

JS

var iframe = document.createElement('iframe');
iframe.frameBorder = 1;
iframe.width = "500px";
iframe.height = "250px";
iframe.id = "iframe";
iframe.onload = function()
{
    var doc = iframe.contentDocument || iframe.contentWindow.document;
    var el = doc.createElement('h2');
    el.id="myH2";
    el.className="red";
    el.style.color="red";
    el.style.cursor="pointer";
    el.textContent = "Click me";
    el.onclick=doSomething;
    doc.body.appendChild(el);
}
document.getElementById("myDiv").appendChild(iframe);
function doSomething()
{
    alert("OK");
}​

这是一把小提琴。

如果将onclick="doSomething();"更改为onclick="top.doSomething();,它将起作用。因为复制的h2在当前窗口中查找doSomething函数,而在iframe中没有doSomething函数。

如果您使用top关键字,它将在顶部窗口中显示函数。在iframe中,这意味着查找父对象,在parent中查找self,这在parent和iframe都有效。除非不存在其他家长。