Cross-Domain iframe Resizer on NextJS?

1.2k views Asked by At

I have a NextJS project that will be loaded through an Iframe. The content of the page is dynamic and the height of the page constantly changes. Instead of using scroll, I want the Iframe to adjust its height according to its content's height.

I have tried using https://www.npmjs.com/package/iframe-resizer-react but it seems I have an issue on how to load the iframeResizer.contentWindow.min.js.

Need help, Can't find any other answers/sources.

2

There are 2 answers

3
David Bradshaw On

You need to add that file to every page you load into the iFrame

0
Lafif Astahdziq On

You need to import the contentWindow script from the iframe resizer to your component, and set the callback (if needed)

import "iframe-resizer/js/iframeResizer.contentWindow";
import { useEffect, useState } from "react";


function Component() {

  useEffect(() => {
    window.iFrameResizer = {
      onMessage: function (message) {
        alert('Got message from parent');
        console.log('message', message);
      },
    };
  }, []);

  return <div>Your content</div>;
}

export default Component;

iframe resizer does require the window so make sure it only runs on the client by importing the component using next/dynamic

import dynamic from "next/dynamic"
const Component = dynamic(() => import("components/Component"), {
  ssr: false,
})

function Page(props) {
  return <Component {...props} />
}

export default Page;