function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Jake BullardJake Bullard 

Get iFrame body or scroll height in LWC?

I am attempting to use the code below to get the height of content within an iFrame so I can resize the iFrame height to fit its content. However, when I run it I get Uncaught TypeError: Cannot read properties of undefined (reading 'body'). 

Why can't seem to access the iFrame body?
 
<template>
  <div class="iframe-container">
    <iframe src={url} onload={handleLoad} style={iframeStyle}></iframe>
  </div>
</template>

<script>
import { LightningElement, track } from 'lwc';

export default class IframeExample extends LightningElement {
  @track url = 'https://www.example.com';
  @track iframeStyle = 'height: 0px;';

  handleLoad() {
    const iframe = this.template.querySelector('iframe');
    const iframeHeight = iframe.contentWindow.document.body.scrollHeight;
    this.iframeStyle = `height: ${iframeHeight}px;`;
  }
}
</script>

<style>
.iframe-container {
  position: relative;
  width: 100%;
  padding-bottom: 56.25%; /* 16:9 aspect ratio */
  height: 0;
}

.iframe-container iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border: none;
}
</style>

 
Jake BullardJake Bullard


I tried this but it didn't work. The function only is called once and can't find the body. I also tried running this code in the RenderedCallback and had the same issue. And I also ran tied this function to a button click and clicked the button several seconds after the page loaded, and still no Body found. It's almost as if salesforce can't see the iFrame content like a normal webpage could.

 

handleLoad() {
    const iframe = this.template.querySelector("iframe");
    if (iframe) {
        const iFrameBody = iframe.contentWindow.document.body;
        if (iFrameBody) {
            const iframeHeight = iFrameBody.scrollHeight;
            this.iframeStyle = `height: ${iframeHeight}px;`;
        }
    }
}