iframe onload event doesn’t fire on soft refresh

  iframe, javascript, jquery

I wrote a script to adjust the height of a page (from within an iframe) based on the height of the iframe. I added events that fire:

  1. 1 second after window load
  2. 2 seconds after window load
  3. 3 seconds
    after window load
  4. on iframe scroll
  5. on iframe click
  6. and on page width
    resize

The script works on my device – Windows 10, Chrome, but I’m still getting reports that it doesn’t work on soft refreshes.

Here’s the code. I know it’s hideous:

// Don't fire on height resizing
$h = 0;
$first_keyup_complete = false;
$set_height_on_scroll = false;

$(function () {
   $(window).load(function(){
    $h = $( window ).height();
    setTimeout(function(){ setHeight(); }, 1000);
    setTimeout(function(){ setHeight(); }, 2000);
    setTimeout(function(){ setHeight(); }, 3000);
   });
});

$("#lfform-placeholder iframe").click( function (e) {
  if (!$first_keyup_complete) {
    setHeight();
    $first_keyup_complete = true;
  }
});
$("#lfform-placeholder iframe").scroll( function (e) {
  if (!$set_height_on_scroll) {
    setHeight();
    $set_height_on_scroll = true;
  }
});

$( window ).resize( function(){
  if( $h != $( window ).height() ){
    
    $h = $( window ).height();
  } else {
        setHeight();  
  }  
});

$('.btn2, .btn1, .progress-bar__section.active, .toggle-btn').click(function(){
  setTimeout(function(){ setHeight(); }, 1000);
});


function setHeight() {
  parent.postMessage({ if_height: $('body').outerHeight( true ) }, 'https://example.com/' );
  
};

Here’s the script that accept the post message and adjusts the page height accordingly:

window.addEventListener('load', function(){
  $iframe_height = 0;
  $iframe = document.getElementById('lf-frame-374417');
  window.addEventListener('message', function(e) {
  
  if (e.data.if_height != undefined) {
    $height = Number( e.data.if_height ) + 30; // add 30px to accomodate box shadow on form
      $iframe.setAttribute( 'style', 'height: ' + $height + 'px !important;');
    }
  });
});

Does anyone know how to reliably adjust the height of a parent page, based on the height of an iframe? I feel like I’ve tried everything. They are not same origin, and the height of the iframe is variable (it’s a form with many pages/accordions). I have access to the iframe and the parent.

Source: Ask Javascript Questions

LEAVE A COMMENT