Ionică Bizău
Ionică Bizău

Reputation: 113485

How to avoid an iframe without src to read it's parent HTML?

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).

Upvotes: 0

Views: 701

Answers (4)

m59
m59

Reputation: 43795

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

Upvotes: 3

user652649
user652649

Reputation:

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

Upvotes: 4

smnbbrv
smnbbrv

Reputation: 24581

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.

Upvotes: 0

janfoeh
janfoeh

Reputation: 10328

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.

Upvotes: 0

Related Questions