davidjbradshaw / iframe-resizer-react

The official React interface for Iframe-Resizer

Home Page:https://iframe-resizer.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Share an example setup

ZhengRui opened this issue · comments

suppose app Parent embed app Child through iframe. click the Send Message button, in console we will see child received msg from parent and also parent received reply message from child.

app Parent (nextjs app) served at http://localhost:3000

index.tsx:

import React, { useRef } from 'react';
import IframeResizer, {
  IFrameComponent,
  IFrameObject,
} from 'iframe-resizer-react';

const HomePage = () => {
  const iframeRef = useRef<IFrameObject>(null);
  const iframeUrl = 'http://localhost:8000';

  const sendMessage = () => {
    const iframeWindow = iframeRef.current;
    iframeWindow?.sendMessage('msg from parent', iframeUrl);
  };

  const onMessage = (data: { iframe: IFrameComponent; message: any }) => {
    console.log('parent received', data.message);
  };

  return (
    <>
      <button onClick={sendMessage}>Send Message</button>
      <IframeResizer
        checkOrigin
        src={iframeUrl}
        frameBorder='0'
        forwardRef={iframeRef}
        onMessage={onMessage}
      />
    </>
  );
};

export default HomePage;

app Child (a minimum react app) served at http://localhost:8000

index.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <script src="js/iframeResizer.contentWindow.min.js"></script>
  <title>Child UI</title>
</head>

<body>
  <div id="ui"></div>
</body>
</html>

index.tsx

import React from 'react';
import ReactDOM from 'react-dom';
import './styles/ui.css';

import APP from './ui';

ReactDOM.render(<APP />, document.getElementById('ui'));

ui.tsx

import React from 'react';

interface iframeWindow extends Window {
  iFrameResizer: {
    targetOrigin?: string;
    onMessage?: Function;
  };
  parentIFrame?: any;
}
declare let window: iframeWindow;

const App = () => {
  const parentUrl = 'http://localhost:3000';

  window.iFrameResizer = {
    targetOrigin: parentUrl,
    onMessage: (message: any) => {
      console.log('child received', message);
      if ('parentIFrame' in window) {
        window.parentIFrame.sendMessage('msg from child', parentUrl);
      }
    },
  };

  return (
    <div className='bg-indigo-400 h-64'>
        i am the child
    </div>
  );
};

export default App;

ui.css

@tailwind base;
@tailwind components;
@tailwind utilities;
.
├── js
│   └── iframeResizer.contentWindow.min.js
├── index.html
├── index.tsx
├── styles
│   └── ui.css
└── ui.tsx