0
votes

I have an iframe without src attribute. I set it's HTML from JavaScript side.

The problem is that if I load a script that contains $("body").html() it returns the body's html of the parent document while I am expecting to get the iframe's body html.

How can I avoid such a behaviour?

I set the iframe HTML using:

$(".myResult").contents().find("html").html(myHtmlToLoad);

Here is a JSFIDDLE where I reproduced the issue. I am expecting the textarea value to return calling $(body).html() (inside of the iframe), but it returns the HTML of the entire page (that contains the iframe).

4
any specific reason it has to be an iframe? It seems like there should be better alternatives if you are explicitly controlling the contents. - Tim Seguine
@Tim I would like to be a separate document. - Ionică Bizău
Is this for user generated content, then, or something along those lines? - Tim Seguine
@Tim Yes, basically the user writes in a textarea his HTML and that HTML is loaded in iframe. But I see that it fails for such a call... - Ionică Bizău
Ok, well even if you get it to work the way you want, there is a security issue. As far as I know, this won't protect you against cross site scripting vulnerabilities because it doesn't violate the same origin policy. If the content is saved and is visible to users other than the current one, they could sniff cookies for example. - Tim Seguine

4 Answers

4
votes
var ifrm = $(".result:first")[0]; 
ifrm.contentDocument.body.textContent = ""; 
var htmlDocumentStr = $(".html").val(); 
ifrm.contentDocument.write(htmlDocumentStr);
3
votes

If I understood your question, you want to get the html of the iframe. Were you looking for this?

var $iframe = $(".myResult");
console.log($('body', $iframe.contents());

You can also get a reference to the iframe's DOM with myIframe.contentDocument

0
votes

By using html(myHtmlToLoad), you are not writing into the iframe document; you are appending child elements to the element, but are still on the parent.

Take a look at this answer on how to access the iframes document.

0
votes

Seems the main problem here is the thing that you are using jQuery from the parent page and this one is an object and not a class, which is assigned to the current page and uses only its body.

Since you are in the iframe, jQuery is still assigned to the parent document.

Your solution should be to especially load jQuery to an "iframe", probably with .noConflict() mode and use it inside of an iframe's JavaScript.

E.g.:

<script ...> // attach new jQuery to iframe

var $$ = jQuery.noConflict(); // make new object for iframe

$$("body")... // use

Hope this helps.