JavaScript dynamically loaded into iframe runs in

2019-07-25 11:52发布

问题:

I have an iframe and I load some html+javascript into it dynamically with the following code:

var allMyCode = "<div id='test'>html code</div> <script type='text/javascript'>alert(document.getElementById('test').innerHTML);<\/script>";
$("#myFrame").contents().find("body").html(allMyCode);

The problem is I would like this to alert the text 'html code' but it actually gets the html in the div in the parent with the id of 'test', so it's not referencing itself. I've shown this in this fiddle: http://jsfiddle.net/BNG4n/

Why is it doing this, how can I make the JavaScript run on its own scope!?

回答1:

Because jQuery executes the script element before setting the html of the iframe's body element which will always be in parent scope.

You can try to create a script element and append inside iframe's body it will work as expected.

Something like this.

var allMyCode = "<div id='test'>html code</div>";
$("#myFrame").contents().find("body").html(allMyCode);
var el = document.createElement("script");
el.setAttribute("type","text/javascript");
el.innerHTML = "alert(document.getElementById('test').innerHTML);";
$("#myFrame").contents().find("body")[0].appendChild(el);

Working demo - http://jsfiddle.net/BNG4n/1/



回答2:

The problem is you are referring to document in your js which still refers to the parent document as far as javascript is concerned at this point.

Instead you have to find the frame first(document.getElementById('myFrame')), then find the HTML content from within the test id in the frame(contentWindow.document) like so:

var allMyCode = "<div id='test'>html code</div> <script type='text/javascript'>alert(document.getElementById('myFrame').contentWindow.document.getElementById('test').innerHTML);<\/script>";