Dynamically Resizing Kibana iFrames with Javascript and HTML

19 Jan 2018

If you’re struggling to dynamically resize your Kibana iFrames, you will need two things: Javascript and HTML.

Below is some inline Javascript that will be run onload for each iframe. It is important to note that this script will only work on Kibana tables - not other types of visualizations.

Basically, the script checks to see if the Kibana table has loaded yet - if not, it resets the function with a recursive loop.

Once the Kibana iframe’s table has loaded, we grab that height, and resize the iframe accordingly.

<script>
/* Waits 1 second then checks the iframe again */
function wait_for_load(id) {
  return setTimeout(() => setIframeHeight(id), 1000)
}

/* 
   Called by each iframe onload. 
   Checks if the Kibana table has loaded
   And resizes the iframe when it does
*/
function setIframeHeight(id) {
  if (!id) return;
  const ifrm = document.getElementById(id); // Get our iFrame element using the id
  if (!ifrm) return;

  // If the Kibana iframe table hasn't fully loaded yet, restart this function after a wait
  if (!ifrm.contentDocument || !ifrm.contentDocument.body || 
      ifrm.contentDocument.body.getElementsByTagName('table').length === 0) {
    return wait_for_load(id)
  }

  // Finally! The table has loaded. Let's get the table height and resize the iframe
  const table_height = ifrm.contentDocument.body.getElementsByTagName('table')[0].offsetHeight + 46;
  // The extra 46px of padding helps us avoid IE and Chrome scrollbars on Windows
  ifrm.style.height = table_height + 'px';  
  console.log('We exited the loop for ' + id + ' after setting a height of ' + table_height + 'px');
}
</script>

<!-- Note that the iframes have their onload attribute set to call the above functions -->
<div>
    <iframe id="table1" style="width: 100%;" 
            src="http://your-kibana-source1" 
            frameborder="0" scrolling="no" 
            onload="setIframeHeight(this.id)">
    </iframe>
    <iframe id="table2" style="width: 100%;" 
            src="your-kibana-source2" 
            frameborder="0" scrolling="no" 
            onload="setIframeHeight(this.id)">
    </iframe>
</div>