You need to sign in to do that
Don't have an account?
Jake 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?
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>
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.