强制iframe评估其javascript? [英] Force iframe to evaluate its javascript?

查看:188
本文介绍了强制iframe评估其javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

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

我需要将html推入iframe的主体,我需要推送javascript以允许此方式工作的方式将字符串转换为iframe的脚本。

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.

推荐答案

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

这是小提琴

这篇关于强制iframe评估其javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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