2

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.

4
  • How you want to call the function doSomethinh() from parent window ? need to clarify. Commented Mar 7, 2012 at 19:01
  • You can a function in the iframe from parent window like (assuming targetFrame is iframe id) document.getElementById('targetFrame').contentWindow.doSomething(); Commented Mar 7, 2012 at 19:04
  • 1
    Sorry, didn't realize my post didn't format how I wanted it to, take a look at it again. Commented Mar 7, 2012 at 19:23
  • I want the h2 tag to be pushed INto the iframe body, and from within the iframe clicking the h2 element should call its javascript function which has also been pushed into the iframe. Commented Mar 7, 2012 at 19:24

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.