Make iframe automatically adjust height according to the contents

Hello, is it possible to make iframe automatically adjust height according to the contents? Because I am using the iframe component in one of my views, and it is not adjusting to the height of the content of the iframe.

Hi,

The Iframe component does not have any smartness regarding autosizing based on content.

And this is not really a Appfarm problem, it’s more a web development problem. There is no good way to find the height from the content of an Iframe because of same-origin policy. This means that unless the website you are trying to put in a Iframe is coming from the same origin, we need to use other methods of getting the height of the page.

So now we have two options based on the setup:

  1. The iframe you are trying to embed is from the same domain( another appfarm app in the same solution):
    Then you should be able to use a coded component with the following code in the script section:
const iframe = document.createElement('iframe')
iframe.src = 'https://wikipedia.org/wiki/Main_Page';
iframe.id = "content"
iframe.style.width = "100%"
iframe.onload = () => {
    iframe.height = iframe.contentWindow.document.body.scrollHeight + "px"
}

appfarm.element.appendChild(iframe);
  1. The website you are trying to embed is coming from another origin (eks: another domain):
    The one of your options is to use the window.postMessage() method, that is designed to safely enables cross-origin communication between window objects.

This approach presupposes that the website you are trying to embed in a iFrame is sending messages for you to read, or that you can edit the source code to send out the message you need to read in the Appfarm app.

Link to docs for window.postMessage():

This message should contain the height of the content, so that you then can edit the height of the iFrame.

Hopefully this wall of text will help you out :smiley:

3 Likes