Force iframe to evaluate its javascript?

2019-02-27 21:28发布

I'm dynamically creating an iframe and at some point I need to insert javascript into it. I can add the tag with the string just fine, but is there a way to force the iframe to re-evaluate its scripts so the javascript is executable?

Simple example of what needs to be done is, user provides:

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

and

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

I need to push the html into the body of the iframe, and I need to push the javascript string into the scripts of the iframe in a way that will allow this to work.

2条回答
做自己的国王
2楼-- · 2019-02-27 21:47

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");
}​

Here is a fiddle.

查看更多
何必那么认真
3楼-- · 2019-02-27 21:51

If you change onclick="doSomething();" to onclick="top.doSomething(); it will work. Because copied h2 looks doSomething function on current window, and in iframe there is no doSomething function.

If you use top keyword, it will look function in top window. In iframe that means look for parent, and in parent look for self, and it will work in parent and in iframe either. Unless there is no another parent exists.

查看更多
登录 后发表回答