I am want to be able to set the height of my iframe to automatically stretch to fit the content it is loading.

I however want to ensure this does not go over a certain height eg: 690px.


Does anyone have an idea of how to go about this ?

Dani AI

Generated

wanted an iframe that auto-sizes to its content but never exceeds 690px. correctly pointed out that pulling the content into a DIV (AJAX/server-side proxy) is often the simplest option when you control or can fetch the source. posted a fixed 690x690 iframe as a fallback, but that does not adapt.

If the framed page is same-origin, the parent can read the iframe document and set height on load (and on later changes). Measure with documentElement.scrollHeight or body.scrollHeight, then clamp to 690px. Example parent-side routine:

// parent (same-origin)
var MAX = 690;
function resizeI(iframe) {
  try {
    var doc = iframe.contentDocument || iframe.contentWindow.document;
    var h = Math.max(doc.documentElement.scrollHeight, doc.body.scrollHeight);
    iframe.style.height = Math.min(h, MAX) + 'px';
  } catch (e) {
    iframe.style.height = MAX + 'px';
  }
}
var f = document.getElementById('myFrame');
f.addEventListener('load', function(){ resizeI(f); });

If the iframe is cross-origin, use postMessage: the framed page measures its height and posts it to the parent; the parent listens, validates e.origin, and applies the height (clamped). Child and parent snippets:

// child (framed page)
function sendHeight() {
  var h = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
  window.parent.postMessage({type:'height', height:h}, 'https://example.com');
}
window.addEventListener('load', sendHeight);
// parent (receives)
window.addEventListener('message', function(e){
  if (e.origin !== 'https://example.com') return; // validate origin
  if (e.data && e.data.type === 'height') {
    var h = Math.min(e.data.height, 690);
    document.getElementById('myFrame').style.height = h + 'px';
  }
});

Notes: verify origins for security, re-measure after images or dynamic DOM changes (use image load events or a MutationObserver), and fall back to scrollable container if you cannot modify the framed page. See Window.postMessage and the Same-origin policy for details.

Recommended Answers

All 2 Replies

I would sugguest going Jquery. Use ajax to pull content into a DIV with a max height of 690px. Since the div will automatically size depending on the content as well as just be a whole lot neater

Try this :) I use it and works

<iframe src="" width="690" height="690" scrolling="no" frameborder="0" ></iframe>

In this way the iframe window will be always 690x690

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.