0

As the title, how to resize appened iframe to content? I have already referred other questions:

, but it is still not working. The following are my codes:

$(function() {
  $('#appendIframeHere').append("<iframe src=\"http://www.w3schools.com/\"></iframe>");
  var iframe = $('#appendIframeHere').find('iframe');
  iframe.css("width", "100%");
  iframe.css("height", iframe.contents().find('body').height() );
  $('#appendIframeHere').text(iframe.contents().find('body').height());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div id="appendIframeHere"></div>

------------------------------------------------------------update------------------------------------------------------------

enter image description here I use the same way to get height() but it has different value, 0 and 2786. I tried to add a callback function to append() but I have seen some reference said that append() complete immediately so I don't have to use callback. After that I also tried promise().done(function(){...}) to append() but it still get different value from js file and console.

Kuldeep Bhimte
  • 961
  • 1
  • 10
  • 25
Lynn Chen
  • 89
  • 1
  • 8
  • 1
    Check the console: `Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "null" from accessing a cross-origin frame`. This is because the Same Origin Policy is stopping you from accessing the content of a third-party domain through an iframe. There is nothing you can do to stop this as it's a security feature. Also note that jQuery 1.2.3 is *incredibly* outdated. I would strongly suggest you upgrade. I'd also suggest you stop using W3Schools as a guide as their information is usually incorrect and often outdated - as in this example. – Rory McCrossan Nov 15 '16 at 10:09
  • @RoryMcCrossan Um...okay, my bad! This is not a good example. My real problem is to link other `html` in the same folder. – Lynn Chen Nov 15 '16 at 10:13
  • Perhaps you can also try: `$('#appendIframeHere iframe').style.height = $('#appendIframeHere iframe').contentWindow.document.body.scrollHeight + 'px';` – Ren Nov 15 '16 at 10:52
  • @Ren I tried your way but there was an error message saying cannot read property `document` of undefined. – Lynn Chen Nov 16 '16 at 00:52
  • 1
    Oh, looks like problem is due to cross-domain iframes, so we don't have access to the child DOM. Maybe you can make use of pluggins like: http://davidjbradshaw.github.io/iframe-resizer/ made for such purposes. – Ren Nov 16 '16 at 12:33

0 Answers0