49

Here is my situation.

I have a file called iframe.html, which contains the code to for a image slideshow. The code is somewhat like

<html>
  <head>
    <!-- Have added title and js files (jquery, slideshow.js) etc. -->
  </head>

  <body>
    <!-- Contains the images which are rendered as slidehow. -->
    <!-- have hierarchy like 'div' inside 'div' etc. -->
  </body>
</html>

Users can use the embed code to add the slideshow to their blogs or websites (can be from different domains). Let's say a user has to embed the slideshow in index.html, they can add by adding following lines:

<iframe id="iframe" src="path_to_iframe.html" width="480" height="320" scrolling="no" frameborder="0"></iframe>

This will bring the complete HTML code from iframe.html to index.html, now I need a way to access the elements in the iframe to adjust some of their properties.

Like in the code the width and the height of the iframe are set by the user to some fix dimensions. I would like to adjust the size of the slideshow (and images contained) to the size of the iframe container. What is the best way to do this?

I tried with no success to access the iframe components from index.html by something like

$('#iframe').contents();

but get the error:

TypeError: Cannot call method 'contents' of null

So, I think to implement the logic in iframe.html where the slideshow should check the width and height of parent and set its height accordingly.

I am pretty much confused, hope my question makes sense to most. Please feel free to ask further explanation. Your help is appreciated.

4
  • Possible issue that is visible in your description is that you add jQuery.js in iframe.html and not index.html but write the code within index.html
    – Knaģis
    Commented Apr 19, 2013 at 11:25
  • @Knaģis I have added the jQuery.js file to iframe.html, and not index.html
    – Ajit S
    Commented Apr 19, 2013 at 11:27
  • If index.html does not have a reference to jquery.js you can't use $() syntax in scripts that are there (JavaScript references are isolated to the window/frame).
    – Knaģis
    Commented Apr 19, 2013 at 11:30
  • @Knaģis I think you might be right. I've got this working using the solution I accepted (with javascript). But, when I use console of the browser, and type in $ it does return function. I think the jQuery loaded in the iframe might be accessible outside as well.
    – Ajit S
    Commented Apr 19, 2013 at 11:37

10 Answers 10

64

This line will retrieve the whole HTML code of the frame. By using other methods instead of innerHTML you can traverse DOM of the inner document.

document.getElementById('iframe').contentWindow.document.body.innerHTML

Thing to remember is that this will work only if the frame source is on the same domain. If it is from a different domain, cross-site-scripting (XSS) protection will kick in.

9
  • 1
    Thank you. The iframe is on same domain. The above code returns undefined.
    – Ajit S
    Commented Apr 19, 2013 at 11:28
  • 1
    what browser and version are you using?
    – Knaģis
    Commented Apr 19, 2013 at 11:31
  • also I did make a mistake in the script - document.innerHTML is empty, while document.body.innerHTML is not.
    – Knaģis
    Commented Apr 19, 2013 at 11:33
  • 1
    I am confused, the question asked for jQuery - important since I need to find all of a certain class within the iframe and change it's CSS
    – PandaWood
    Commented Mar 17, 2016 at 23:45
  • 1
    @PandaWood, I agree that the answer doesn't quite go the whole distance in terms of "using jQuery" as the OP specified. I think you want something like this: var innerDocAsJQueryObject = $(document.getElementById("iframe").contentWindow.document); Then you can easily change the CSS of elements inside the iframe, like this: innerDocAsJQueryObject.find(".yourClass").css("background-color", "purple"); Commented May 30, 2018 at 17:05
47

Try this code:

$('#iframe').contents().find("html").html();

This will return all the html in your iframe. Instead of .find("html") you can use any selector you want eg: .find('body'),.find('div#mydiv').

3
  • 4
    Just a note, this won't work if the iframe document is hosted on another domain or same domain but different port number.
    – user6269864
    Commented Dec 19, 2016 at 8:02
  • it will not work anyway - in the question above you can see that src for iframe is local file
    – Sasha Bond
    Commented Sep 24, 2018 at 16:50
  • helped me out big time!
    – philip
    Commented Oct 29, 2018 at 19:39
6
var iframe = document.getElementById('iframe');
  $(iframe).contents().find("html").html();
0
5
$(editFrame).contents().find("html").html();
3

this works for me because it works fine in ie8.

$('#iframe').contents().find("html").html();

but if you like to use javascript aside for jquery you may use like this

var iframe = document.getElementById('iframecontent');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
var val_1 = innerDoc.getElementById('value_1').value;
2

If you have Div as follows in one Iframe

 <iframe id="ifrmReportViewer" name="ifrmReportViewer" frameborder="0" width="980"

     <div id="EndLetterSequenceNoToShow" runat="server"> 11441551 </div> Or

     <form id="form1" runat="server">        
       <div style="clear: both; width: 998px; margin: 0 auto;" id="divInnerForm">          

            Some Text

        </div>
     </form>
 </iframe>

Then you can find the text of those Div using the following code

var iContentBody = $("#ifrmReportViewer").contents().find("body");
var endLetterSequenceNo = iContentBody.find("#EndLetterSequenceNoToShow").text();

var divInnerFormText = iContentBody.find("#divInnerForm").text();

I hope this will help someone.

1
  • there is no div inside iframe - iframe has local src
    – Sasha Bond
    Commented Sep 24, 2018 at 16:51
1

Just for reference's sake. This is how to do it with JQuery (useful for instance when you cannot query by element id):

$('#iframe').get(0).contentWindow.document.body.innerHTML
0
0

This can be another solution if jquery is loaded in iframe.html.

$('#iframe')[0].contentWindow.$("html").html()
0

Why not try Ajax, check a code part 1 or part 2 (use comment).

$(document).ready(function(){ 
	console.clear();
/*
    // PART 1 ERROR
    // Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Sandbox access violation: Blocked a frame at "http://stacksnippets.net" from accessing a frame at "null".  Both frames are sandboxed and lack the "allow-same-origin" flag.
	console.log("PART 1:: ");
	console.log($('iframe#sandro').contents().find("html").html());
*/
	// PART 2
	$.ajax({
		url: $("iframe#sandro").attr("src"),
		type: 'GET',
		dataType: 'html'
	}).done(function(html) {
		console.log("PART 2:: ");
		console.log(html);
	});

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<html>
<body>
<iframe id="sandro" src="https://jsfiddle.net/robots.txt"></iframe>
</body>
</html>

1
-2
$('#iframe').load(function() {
    var src = $('#iframe').contents().find("html").html();
    alert(src);
});
1
  • please add description: why this will help?
    – zohar
    Commented Feb 25, 2015 at 9:49

Not the answer you're looking for? Browse other questions tagged or ask your own question.