Prasanna Natarajan

Javascript and iFrames

Consider this web app requirement:

Here’s how the hosting page might look like:

<html>
<head>
  <style>
    iframe{
      width:100%;
    }
  </style>

  <script src="/js/urlsearchparams_polyfill.js"></script>
  <script src="/js/iframeResizer.min.js"></script>

  <script>
  document.addEventListener('DOMContentLoaded', function(){
    var currentParams = new URLSearchParams(window.location.search);
    var iframe = document.createElement('iframe');
    iframe.src = 'http://iframesourcepage.com/path?' + currentParams.toString();
    document.body.appendChild(iframe);
    var iframes = window.iFrameResize({
      log: false,
      autoResize: true,
      heightCalculationMethod: 'max',
    });
  });
  </script>
</head>


<body>
</body>
</html>

What this does is: * on page load, it extracts the query strings from url using the urlsearchparams polyfill * an iframe element is dynamically created with its url appended with these query strings. The created iframe is attached to the current page’s html document * the iframe resizer is initialized with options that allow it to expand/shrink automatically based on its content’s size.

For this to work as intended, the hosted page within the iframe must have the 2nd js from the resizer lib. Add this to the <head> of that page:

<script src="/assets/iframeResizer.contentWindow.min.js"></script>

Now things will work as expected.