Blog

Thoughts from my daily grind

Auto Determine Iframe Size based on Embedded Page

Posted by Ziyan Junaideen |Published: 28 August 2020 |Category: Code
Browser |

Iframes - or the Inline Frame HTML element is a very useful tool. It allows us to embed multiple pages in within a host page. These pages can be on the same domain or from another domain (cross domain). Each frame will have its own session. While that is cool, you know what would have been better? The ability to resize to the embedded page size even if it changes later on.

Fortunately there is a plugin that can help you achieve that. Unfortunately it needs JS to be included in both sides of the page.

Welcome iframe-resizer. Here is a simple example.

Scenario

Assume you have 2 domains namely www.mysite.com and you.embeddableservice.com. You want to embed the page at you.embeddableservice.com in www.mysite.com/service. The embedded page fluid. Thus it will fit the available width. How ever it is dynamic. Meaning based on user input it can get tall.

You need to:

  • On page load - resize the iframe to fit the width
  • As the user updates the form - if it gets taller - to accommodate so that there is no need to scroll within the iframe.

This is how you do it if you are embeddedservice.com or have the ability to include JS to that page.

Implementation

On the page that would get embedded (you.embeddedservice.com) include this script

<!DOCTYPE html>
<html>
<head>
<script src="https://raw.githubusercontent.com/davidjbradshaw/iframe-resizer/master/js/iframeResizer.min.js" type="text/javascript"></script>
</head>
<!-- Rest of the body -->
</html>

On the page that is going to have the iframe, do some thing like this...

<!DOCTYPE html>
<html>
<body>
<style>iframe{width:100%, border: none;}</style>
<script src="https://raw.github.com/davidjbradshaw/iframe-resizer/master/js/iframeResizer.contentWindow.min.js" type="text/javascript"></script>
<iframe src="https://you.embeddedservice.com" scrolling="no" title="Iframe Example"></iframe>
<script>iFrameResize({log:true})</script>
</body>
</html>

When the iRameResize is triggered in the content window, it will communicate with the embedded page and resize the iframe according to needs.

That is it. Hope it was helpful.

Tags
About the Author

Ziyan Junaideen -

Ziyan is an expert Ruby on Rails web developer with 8 years of experience specializing in SaaS applications. He spends his free time he writes blogs, drawing on his iPad, shoots photos.

Comments