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.

Kaspar Lee
  • 5,446
  • 4
  • 31
  • 54
Ajit S
  • 1,341
  • 1
  • 13
  • 32
  • 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 Apr 19 '13 at 11:25
  • @Knaģis I have added the `jQuery.js` file to `iframe.html`, and not `index.html` – Ajit S Apr 19 '13 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 Apr 19 '13 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 Apr 19 '13 at 11:37

10 Answers10

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.

Knaģis
  • 20,827
  • 7
  • 66
  • 80
  • 1
    Thank you. The iframe is on same domain. The above code returns `undefined`. – Ajit S Apr 19 '13 at 11:28
  • 1
    what browser and version are you using? – Knaģis Apr 19 '13 at 11:31
  • also I did make a mistake in the script - `document.innerHTML` is empty, while `document.body.innerHTML` is not. – Knaģis Apr 19 '13 at 11:33
  • I tried this on FF 20 and Chrome 26.0.14, and jQuery version 1.7.1 – Ajit S Apr 19 '13 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 Mar 17 '16 at 23:45
  • I can't get the elements value, which has been typed on input box. – praba May 17 '17 at 01:03
  • 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");` – Dan Robinson May 30 '18 at 17:05
  • u missed the question - iframe source is local file, your solution returns empty string – Sasha Bond Sep 24 '18 at 16:49
  • @SashaBond where does it say in the question that local filesystem instead of http is used? – Knaģis Sep 26 '18 at 12:43
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').

Chamara Keragala
  • 5,627
  • 10
  • 40
  • 58
6
var iframe = document.getElementById('iframe');
  $(iframe).contents().find("html").html();
Dolo
  • 966
  • 14
  • 28
5
$(editFrame).contents().find("html").html();
Arun Yokesh
  • 1,346
  • 17
  • 19
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;
Hermes
  • 41
  • 3
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.

Md. Nazrul Islam
  • 2,809
  • 26
  • 31
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
mxro
  • 6,588
  • 4
  • 35
  • 38
0

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

$('#iframe')[0].contentWindow.$("html").html()
toshi
  • 2,757
  • 1
  • 16
  • 12
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>
KingRider
  • 2,140
  • 25
  • 23
-2
$('#iframe').load(function() {
    var src = $('#iframe').contents().find("html").html();
    alert(src);
});
guradio
  • 15,524
  • 4
  • 36
  • 57
akash
  • 9