简体   繁体   中英

Run javascript in a dynamically created iframe

I have a tool which generates some html+javascript code, it shows the code in one div and then shows a preview of what the code displays like in an iframe.

Here's a quick fiddle which shows this... http://jsfiddle.net/Zv4zU/

But the javascript within the iframe never runs even though if you inspect the iframe the javascript is definitely in there. How can I get the javascript to run by itself?

See this jsfiddle for a solution!

Edit: As Jonathan pointed out, I should also post the code here:

var html = "html code <script type='text/javascript'>alert('OK');<\/script>";
$("#myFrame").contents().find("body").html(html);

I'm bit update your script to really start JS in the iframe:

var script = "alert('OK');document.body.innerHTML = 'hello!'";
myFrame.get(0).contentWindow.eval(script);

see jsfeedle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM