@iframe-resizer/react
Version:
Keep iframes sized to their content.
110 lines (99 loc) • 3.19 kB
JavaScript
/*!
* @preserve
*
* @module iframe-resizer/react 5.4.6 (esm) - 2025-04-24
*
* @license GPL-3.0 for non-commercial use only.
* For commercial use, you must purchase a license from
* https://iframe-resizer.com/pricing
*
* @description Keep same and cross domain iFrames sized to their content
*
* @author David J. Bradshaw <info@iframe-resizer.com>
*
* @see {@link https://iframe-resizer.com}
*
* @copyright (c) 2013 - 2025, David J. Bradshaw. All rights reserved.
*/
import _extends from '@babel/runtime/helpers/extends';
import connectResizer from '@iframe-resizer/core';
import acg from 'auto-console-group';
import React, { useRef, useEffect, useImperativeHandle } from 'react';
const filterIframeAttribs = props => {
const {
license,
bodyBackground,
bodyMargin,
bodyPadding,
checkOrigin,
direction,
inPageLinks,
log,
offset,
offsetHeight,
offsetWidth,
scrolling,
tolerance,
warningTimeout,
waitForLoad,
onClosed,
onReady,
onMessage,
onResized,
...iframeProps
} = props;
return iframeProps;
};
const esModuleInterop = mod =>
// eslint-disable-next-line no-underscore-dangle
mod?.__esModule ? mod.default : mod;
// Deal with UMD not converting default exports to named exports
const createAutoConsoleGroup = esModuleInterop(acg);
// TODO: Add support for React.forwardRef() in next major version (Breaking change)
function IframeResizer(props) {
// eslint-disable-next-line react/prop-types
const {
forwardRef,
...rest
} = props;
const filteredProps = filterIframeAttribs(rest);
const iframeRef = useRef(null);
const consoleGroup = createAutoConsoleGroup();
const onClose = () => {
consoleGroup.event('onClose');
consoleGroup.warn(`Close event ignored, to remove the iframe update your React component.`);
return false;
};
// This hook is only run once, as once iframe-resizer is bound, it will
// deal with changes to the element and does not need recalling
useEffect(() => {
const iframe = iframeRef.current;
const resizerOptions = {
...rest,
onClose
};
consoleGroup.label(`react(${iframe.id})`);
consoleGroup.event('setup');
const resizer = connectResizer(resizerOptions)(iframe);
consoleGroup.expand(resizerOptions.logExpand);
if (rest.log) consoleGroup.log('Created React component');
return () => {
consoleGroup.endAutoGroup();
resizer?.disconnect();
};
}, []); // eslint-disable-line react-hooks/exhaustive-deps
useImperativeHandle(forwardRef, () => ({
getRef: () => iframeRef,
getElement: () => iframeRef.current,
resize: () => iframeRef.current.iframeResizer.resize(),
moveToAnchor: anchor => iframeRef.current.iframeResizer.moveToAnchor(anchor),
sendMessage: (message, targetOrigin) => {
iframeRef.current.iframeResizer.sendMessage(message, targetOrigin);
}
}));
// eslint-disable-next-line jsx-a11y/iframe-has-title
return /*#__PURE__*/React.createElement("iframe", _extends({}, filteredProps, {
ref: iframeRef
}));
}
export { IframeResizer as default };