0.0.3 • Published 8 months ago
simple-iframe-resizer v0.0.3
simple-iframe-resizer
simple-iframe-resizer helps you to auto resize cross-domain iframe dimensions based on the content size
It works as react hooks, and is only compatible with React>=16.8.0
Installation
# npm
npm install simple-iframe-resizer --save
# yarn
yarn add simple-iframe-resizer
# pnpm
pnpm add simple-iframe-resizerBasic Concepts
Two hooks are used in iframe and host respectively, useResizeChild and useResizeParent. For convenience, we treat iframe as child and host as parent.
useResizeChild: used within iframe context.useResizeParent: used within host context that containing a iframe element
Usage
- Name a unique resize event name
Use it in both parent and child side. simple-iframe-resizer will use this event name to communicate between parent and child through postMessage. Make sure the event name is unique to avoid interference.
// Example event name
const RESIZE_EVENT_NAME = '__simple_iframe_resizer_demo_9f9292a4';- On child side
import { useResizeChild } from 'simple-iframe-resizer';
const ChildApp = () => {
const [domRef] = useResizeChild(RESIZE_EVENT_NAME);
return <div ref={domRef}>Hello World</div>;
};- On parent side
import { useResizeParent } from 'simple-iframe-resizer';
const ParentApp = () => {
const iframeRef = useRef<HTMLIFrameElement>(null);
const iframeWindowRef = useRef<Window | undefined>();
useEffect(() => {
iframeWindowRef.current = iframeRef.current?.contentWindow || undefined;
}, []);
const [rect] = useResizeParent(RESIZE_EVENT_NAME, iframeWindowRef);
return (
<iframe
ref={iframeRef}
src="https://www.example.com"
height={rect.height || '100%'}
width={rect.width || '100%'}
/>
);
};Advanced Usage
- Trigger
onUnmountevent and reset the iframe height
const [domRef, rpcClient] = useResizeChild(RESIZE_EVENT_NAME);
useEffect(() => {
return () => rpcClient.onUnmount();
}, []);- Manually get dimensions of child from parent
const [rect, childRpcClient] = useResizeParent(
RESIZE_EVENT_NAME,
iframeWindowRef,
);
useEffect(() => {
childRpcClient.getSize().then((rect) => {
console.log(rect);
});
}, []);Type Definition
interface ParentFunctions {
onResize: (rect: DOMRectReadOnly) => void;
onUnmount: () => void;
}interface ChildFunctions {
getSize: () => DOMRectReadOnly | undefined;
}declare const useResizeChild: <T extends Element>(
id: string,
) => [React.RefObject<T>, ParentRpcClient | undefined];declare const useResizeParent: (
id: string,
windowRef: React.MutableRefObject<Window | undefined>,
) => [DOMRectReadOnly | undefined, ChildRpcClient | undefined];