UNPKG

@iframe-resizer/parent

Version:

Keep iframes sized to their content.

104 lines (81 loc) 2.65 kB
/*! * @preserve * * @module iframe-resizer/parent 5.5.9 (esm) - 2026-02-06 * * @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 - 2026, David J. Bradshaw. All rights reserved. */ import connectResizer from '@iframe-resizer/core'; const LABEL = 'iframeResizer'; const STRING = 'string'; const OBJECT = 'object'; const UNDEFINED = 'undefined'; const id = `[${LABEL}] `; function createIframeResize() { function setupDisconnectedIframe(element) { const observer = new MutationObserver(() => { if (element.isConnected) { connectWithOptions(element); observer.disconnect(); } }); // Observe changes in the document body for added nodes observer.observe(document.body, { childList: true, subtree: true }); } function setup(element) { switch (true) { case !element: throw new TypeError(`${id}iframe is not defined`) case !element.tagName: throw new TypeError(`${id}Not a valid DOM element`) case element.tagName.toUpperCase() !== 'IFRAME': throw new TypeError( `${id}Expected <IFRAME> tag, found <${element.tagName}>`, ) case !element.isConnected: setupDisconnectedIframe(element); iFrames.push(element); break default: connectWithOptions(element); iFrames.push(element); } } let connectWithOptions; let iFrames; return function (options, target) { if (typeof window === UNDEFINED) return [] // don't run for server side render // Check if document.body exists in browser environment if (!document.body) { throw new TypeError( `${id}document.body is not available. Ensure the DOM is fully loaded before calling iframeResize().`, ) } connectWithOptions = connectResizer(options); iFrames = []; // Only return iFrames passed in on this call switch (typeof target) { case UNDEFINED: case STRING: document.querySelectorAll(target || 'iframe').forEach(setup); break case OBJECT: setup(target); break default: throw new TypeError(`${id}Unexpected data type (${typeof target})`) } return Object.freeze(iFrames) } } const esm = createIframeResize(); export { esm as default };