@iframe-resizer/child 5.2.2-beta.2 → 5.2.2-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.cjs.js CHANGED
@@ -1,21 +1,1659 @@
1
1
  /*!
2
2
  * @preserve
3
3
  *
4
- * @module iframe-resizer/child 5.2.2-beta.2 (cjs) - 2024-07-18
4
+ * @module iframe-resizer/child 5.2.2-beta.3 (cjs) - 2024-07-25
5
5
  *
6
- * @license GPL-3.0 for non-commercial use only.
7
- * For commercial use, you must purchase a license from
8
- * https://iframe-resizer.com/pricing
6
+ * @license GPL-3.0 for non-commercial use only.
7
+ * For commercial use, you must purchase a license from
8
+ * https://iframe-resizer.com/pricing
9
9
  *
10
- * @desciption Keep same and cross domain iFrames sized to their content
10
+ * @description Keep same and cross domain iFrames sized to their content
11
11
  *
12
- * @author David J. Bradshaw <info@iframe-resizer.com>
12
+ * @author David J. Bradshaw <info@iframe-resizer.com>
13
13
  *
14
- * @see {@link https://iframe-resizer.com}
14
+ * @see {@link https://iframe-resizer.com}
15
15
  *
16
16
  * @copyright (c) 2013 - 2024, David J. Bradshaw. All rights reserved.
17
17
  */
18
18
 
19
19
 
20
- "use strict";const e="5.2.2-beta.2",t=10,n="data-iframe-size",o="data-iframe-overflow",i="bottom",r="right",a=(e,t,n,o)=>e.addEventListener(t,n,o||!1),l=["<iy><yi>Puchspk Spjluzl Rlf</><iy><iy>","<iy><yi>Tpzzpun Spjluzl Rlf</><iy><iy>","Aopz spiyhyf pz hchpshisl dpao ivao Jvttlyjphs huk Vwlu-Zvbyjl spjluzlz.<iy><iy><i>Jvttlyjphs Spjluzl</><iy>Mvy jvttlyjphs bzl, <p>pmyhtl-ylzpgly</> ylxbpylz h svd jvza vul aptl spjluzl mll. Mvy tvyl pumvythapvu cpzpa <b>oaawz://pmyhtl-ylzpgly.jvt/wypjpun</>.<iy><iy><i>Vwlu Zvbyjl Spjluzl</><iy>Pm fvb hyl bzpun aopz spiyhyf pu h uvu-jvttlyjphs vwlu zvbyjl wyvqlja aolu fvb jhu bzl pa mvy myll bukly aol alytz vm aol NWS C3 Spjluzl. Av jvumpyt fvb hjjlwa aolzl alytz, wslhzl zla aol <i>spjluzl</> rlf pu <p>pmyhtl-ylzpgly</> vwapvuz av <i>NWSc3</>.<iy><iy>Mvy tvyl pumvythapvu wslhzl zll: <b>oaawz://pmyhtl-ylzpgly.jvt/nws</>","<i>NWSc3 Spjluzl Clyzpvu</><iy><iy>Aopz clyzpvu vm <p>pmyhtl-ylzpgly</> pz ilpun bzlk bukly aol alytz vm aol <i>NWS C3</> spjluzl. Aopz spjluzl hssvdz fvb av bzl <p>pmyhtl-ylzpgly</> pu Vwlu Zvbyjl wyvqljaz, iba pa ylxbpylz fvby wyvqlja av il wbispj, wyvcpkl haaypibapvu huk il spjluzlk bukly clyzpvu 3 vy shaly vm aol NUB Nlulyhs Wbispj Spjluzl.<iy><iy>Pm fvb hyl bzpun aopz spiyhyf pu h uvu-vwlu zvbyjl wyvqlja vy dlizpal, fvb dpss ullk av wbyjohzl h svd jvza vul aptl jvttlyjphs spjluzl.<iy><iy>Mvy tvyl pumvythapvu cpzpa <b>oaawz://pmyhtl-ylzpgly.jvt/wypjpun</>."];Object.fromEntries(["2cgs7fdf4xb","1c9ctcccr4z","1q2pc4eebgb","ueokt0969w","w2zxchhgqz","1umuxblj2e5"].map(((e,t)=>[e,Math.max(0,t-1)])));const s=e=>(e=>e.replaceAll(/[A-Za-z]/g,(e=>String.fromCodePoint((e<="Z"?90:122)>=(e=e.codePointAt(0)+19)?e:e-26))))(l[e]),c=e=>{let t=!1;return function(){return t?void 0:(t=!0,Reflect.apply(e,this,arguments))}},d=e=>e;let u="",m=!1;const f=e=>{u=e.id,m=e.logging},p=e=>e.charAt(0).toUpperCase()+e.slice(1),h=e=>""!=`${e}`&&void 0!==e;function g(e){switch(!0){case!h(e):return"";case h(e.id):return`${e.nodeName.toUpperCase()}#${e.id}`;case h(e.name):return`${e.nodeName.toUpperCase()} (${e.name})`;default:return e.nodeName.toUpperCase()+(h(e.className)?`.${e.className}`:"")}}const y=(...e)=>[`[iframe-resizer][${u}]`,...e].join(" "),v=(...e)=>m&&console?.log(y(...e)),b=(...e)=>console?.info(`[iframe-resizer][${u}]`,...e),z=(...e)=>console?.warn(y(...e)),w=(...e)=>console?.warn((e=>t=>window.chrome?e(t.replaceAll("<br>","\n").replaceAll("<rb>","").replaceAll("</>","").replaceAll("<b>","").replaceAll("<i>","").replaceAll("<u>","")):e(t.replaceAll("<br>","\n").replaceAll(/<[/a-z]+>/gi,"")))(y)(...e)),$=e=>w(e);let S=[];const E=e=>{const t=e.side||i,n=e.onChange||d,r={root:document.documentElement,rootMargin:"0px",threshold:1},a=new WeakSet,l=new IntersectionObserver((e=>{e.forEach((e=>{e.target.toggleAttribute(o,(e=>0===e.boundingClientRect[t]||e.boundingClientRect[t]>e.rootBounds[t])(e))})),S=document.querySelectorAll(`[${o}]`),v("overflowedElements:",S),n()}),r);return e=>e.forEach((e=>{a.has(e)||(l.observe(e),a.add(e))}))},M=()=>S.length>0,j=1e5,P="--ifr-start",T="--ifr-end",C="--ifr-measure",O=[],A=new WeakSet,I=e=>"object"==typeof e&&A.add(e),k=e=>Math.floor(e*j)/j;let R=null,N=null,x={};const L=setInterval((()=>{if(O.length<10)return;if(x.hasTags&&x.len<25)return;O.sort();const e=Math.min(O.reduce(((e,t)=>e+t),0)/O.length,O[Math.floor(O.length/2)]);v("Max time:",Math.max(...O)),e<=4||(clearInterval(L),w(`<rb>Performance Warning</>\n\nCalculating the page size is taking an excessive amount of time (${k(e)}ms).\n\nTo improve performance add the <b>data-iframe-size</> attribute to the ${x.Side.toLowerCase()} most element on the page. For more details see: <u>https://iframe-resizer.com/perf</>.`))}),5e3);function q(e){e.getEntries().forEach((e=>{if(e.name===T){const{duration:t}=performance.measure(C,P,T);!function(e,t){const{Side:n,len:o,hasTags:i,logging:r}=e;x=e,A.has(N)||R===N||i&&o<=1||(r||I(N),R=N,b(`\n${n} position calculated from:\n`,N,`\nParsed ${o} ${i?"tagged":"potentially overflowing"} elements in ${k(t)}ms`))}(e.detail,t),O.push(t),O.length>100&&O.shift()}}))}function B(){new PerformanceObserver(q).observe({entryTypes:["mark"]}),I(document.documentElement),I(document.body)}"undefined"!=typeof document&&"undefined"!=typeof PerformanceObserver&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",B):B()),"undefined"!=typeof window&&function(){const o={contentVisibilityAuto:!0,opacityProperty:!0,visibilityProperty:!0},l={height:()=>(z("Custom height calculation function not defined"),Ve.auto()),width:()=>(z("Custom width calculation function not defined"),Je.auto())},u={bodyOffset:1,bodyScroll:1,offset:1,documentElementOffset:1,documentElementScroll:1,documentElementBoundingClientRect:1,max:1,min:1,grow:1,lowestElement:1},m=128,h={},y="checkVisibility"in window,b="auto",j={reset:1,resetPage:1,init:1},C="[iFrameSizer]",O=C.length,A={max:1,min:1,bodyScroll:1,documentElementScroll:1},I=["body"],k="scroll";let R,x,L=!0,q="",B=0,F="",W=null,D="",H=!0,U=!1,V=!0,J=!1,Z=1,Q=b,X=!0,Y="",G={},K=!1,_=0,ee=!1,te="",ne=d,oe="child",ie=null,re=!1,ae="",le=[],se=window.parent,ce="*",de=0,ue=!1,me="",fe=1,pe=k,he=window,ge=()=>{z("onMessage function not defined")},ye=()=>{},ve=null,be=null;function ze(){var o,d;!function(){const e=e=>"true"===e,t=Y.slice(O).split(":");te=t[0],B=void 0===t[1]?B:Number(t[1]),U=void 0===t[2]?U:e(t[2]),K=void 0===t[3]?K:e(t[3]),L=void 0===t[6]?L:e(t[6]),F=t[7],Q=void 0===t[8]?Q:t[8],q=t[9],D=t[10],de=void 0===t[11]?de:Number(t[11]),G.enable=void 0!==t[12]&&e(t[12]),oe=void 0===t[13]?oe:t[13],pe=void 0===t[14]?pe:t[14],ee=void 0===t[15]?ee:e(t[15]),R=void 0===t[16]?R:Number(t[16]),x=void 0===t[17]?x:Number(t[17]),H=void 0===t[18]?H:e(t[18]),t[19],me=t[20]||me,_=void 0===t[21]?_:Number(t[21])}(),function(){function e(){const e=window.iframeResizer||window.iFrameResizer;v(`Reading data from page: ${JSON.stringify(e)}`),ge=e?.onMessage||ge,ye=e?.onReady||ye,"number"==typeof e?.offset&&(w("<rb>Deprecated option</>\n\n The <b>offset</> option has been renamed to <b>offsetSize</>. Use of the old name will be removed in a future version of <i>iframe-resizer</>."),H&&(R=e?.offset),U&&(x=e?.offset)),"number"==typeof e?.offsetSize&&(H&&(R=e?.offsetSize),U&&(x=e?.offsetSize)),Object.prototype.hasOwnProperty.call(e,"sizeSelector")&&(ae=e.sizeSelector),ce=e?.targetOrigin||ce,Q=e?.heightCalculationMethod||Q,pe=e?.widthCalculationMethod||pe}function t(e,t){return"function"==typeof e&&(v(`Setup custom ${t}CalcMethod`),l[t]=e,e="custom"),e}1!==_&&("iFrameResizer"in window&&Object===window.iFrameResizer.constructor&&(e(),Q=t(Q,"height"),pe=t(pe,"width")),v(`TargetOrigin for parent set to: ${ce}`))}(),v(`Initialising iFrame v${e} (${window.location.href})`),f({id:te,logging:K}),function(){try{re="iframeParentListener"in window.parent}catch(e){v("Cross domain iframe detected.")}}(),_<0?$(`${s(_+2)}${s(2)}`):me.codePointAt(0)>4||_<2&&$(s(3)),me&&""!==me&&"false"!==me?me!==e&&w(`<rb>Version mismatch</>\n\nThe parent and child pages are running different versions of <i>iframe resizer</>.\n\nParent page: ${me} - Child page: ${e}.\n`):w("<rb>Legacy version detected on parent page</>\n\nDetected legacy version of parent page script. It is recommended to update the parent page to use <b>@iframe-resizer/parent</>.\n\nSee <u>https://iframe-resizer.com/setup/</> for more details.\n"),Ce(),Oe(),function(){let e=!1;const t=t=>document.querySelectorAll(`[${t}]`).forEach((o=>{e=!0,o.removeAttribute(t),o.toggleAttribute(n,!0)}));t("data-iframe-height"),t("data-iframe-width"),e&&w("<rb>Deprecated Attributes</>\n \nThe <b>data-iframe-height</> and <b>data-iframe-width</> attributes have been deprecated and replaced with the single <b>data-iframe-size</> attribute. Use of the old attributes will be removed in a future version of <i>iframe-resizer</>.")}(),$e(),H!==U&&(ne=E({onChange:c(we),side:H?i:r})),1!==_&&(he.parentIframe=Object.freeze({autoResize:e=>(!0===e&&!1===L?(L=!0,Ae()):!1===e&&!0===L&&(L=!1,Pe("remove"),ie?.disconnect(),W?.disconnect()),Ke(0,0,"autoResize",JSON.stringify(L)),L),close(){Ke(0,0,"close")},getId:()=>te,getPageInfo(e){if("function"==typeof e)return ve=e,Ke(0,0,"pageInfo"),void w("<rb>Deprecated Method</>\n \nThe <b>getPageInfo()</> method has been deprecated and replaced with <b>getParentProps()</>. Use of this method will be removed in a future version of <i>iframe-resizer</>.\n");ve=null,Ke(0,0,"pageInfoStop")},getParentProps(e){if("function"!=typeof e)throw new TypeError("parentIFrame.getParentProps(callback) callback not a function");return be=e,Ke(0,0,"parentInfo"),()=>{be=null,Ke(0,0,"parentInfoStop")}},getParentProperties(e){w("<rb>Renamed Method</>\n \nThe <b>getParentProperties()</> method has been renamed <b>getParentProps()</>. Use of the old name will be removed in a future version of <i>iframe-resizer</>.\n"),this.getParentProps(e)},moveToAnchor(e){G.findTarget(e)},reset(){Ge("parentIFrame.reset")},scrollBy(e,t){Ke(t,e,"scrollBy")},scrollTo(e,t){Ke(t,e,"scrollTo")},scrollToOffset(e,t){Ke(t,e,"scrollToOffset")},sendMessage(e,t){Ke(0,0,"message",JSON.stringify(e),t)},setHeightCalculationMethod(e){Q=e,Ce()},setWidthCalculationMethod(e){pe=e,Oe()},setTargetOrigin(e){v(`Set targetOrigin: ${e}`),ce=e},resize(e,t){Qe("size",`parentIFrame.size(${e||""}${t?`,${t}`:""})`,e,t)},size(e,t){w("<rb>Deprecated Method</>\n \nThe <b>size()</> method has been deprecated and replaced with <b>resize()</>. Use of this method will be removed in a future version of <i>iframe-resizer</>.\n"),this.resize(e,t)}}),he.parentIFrame=he.parentIframe),function(){function e(e){Ke(0,0,e.type,`${e.screenY}:${e.screenX}`)}function t(t,n){v(`Add event listener: ${n}`),a(window.document,t,e)}!0===ee&&(t("mouseenter","Mouse Enter"),t("mouseleave","Mouse Leave"))}(),G=function(){const e=()=>({x:document.documentElement.scrollLeft,y:document.documentElement.scrollTop});function n(n){const o=n.getBoundingClientRect(),i=e();return{x:parseInt(o.left,t)+parseInt(i.x,t),y:parseInt(o.top,t)+parseInt(i.y,t)}}function o(e){function t(e){const t=n(e);v(`Moving to in page link (#${o}) at x: ${t.x}y: ${t.y}`),Ke(t.y,t.x,"scrollToOffset")}const o=e.split("#")[1]||e,i=decodeURIComponent(o),r=document.getElementById(i)||document.getElementsByName(i)[0];void 0===r?(v(`In page link (#${o}) not found in iFrame, so sending to parent`),Ke(0,0,"inPageLink",`#${o}`)):t(r)}function i(){const{hash:e,href:t}=window.location;""!==e&&"#"!==e&&o(t)}function r(){function e(e){function t(e){e.preventDefault(),o(this.getAttribute("href"))}"#"!==e.getAttribute("href")&&a(e,"click",t)}document.querySelectorAll('a[href^="#"]').forEach(e)}function l(){a(window,"hashchange",i)}function s(){setTimeout(i,m)}function c(){v("Setting up location.hash handlers"),r(),l(),s()}return G.enable?1===_?w("In page linking requires a Professional or Business license. Please see https://iframe-resizer.com/pricing for more details."):c():v("In page linking not enabled"),{findTarget:o}}(),Se(We(document)()),void 0===F&&(F=`${B}px`),Ee("margin",(o="margin",(d=F).includes("-")&&(z(`Negative CSS value ignored for ${o}`),d=""),d)),Ee("background",q),Ee("padding",D),function(){const e=document.createElement("div");e.style.clear="both",e.style.display="block",e.style.height="0",document.body.append(e)}(),function(){const e=e=>e.style.setProperty("height","auto","important");e(document.documentElement),e(document.body),v('HTML & body height set to "auto !important"')}(),Me()}const we=()=>{Qe("init","Init message from host page",void 0,void 0,e),document.title&&""!==document.title&&Ke(0,0,"title",document.title),Ae(),ye(),v("Initialization complete"),v("---")};function $e(){le=document.querySelectorAll(`[${n}]`),J=le.length>0,v(`Tagged elements found: ${J}`)}function Se(e){J?setTimeout(we):ne(e)}function Ee(e,t){void 0!==t&&""!==t&&"null"!==t&&(document.body.style.setProperty(e,t),v(`Body ${e} set to "${t}"`))}function Me(){""!==ae&&(v(`Applying sizeSelector: ${ae}`),document.querySelectorAll(ae).forEach((e=>{v(`Applying data-iframe-size to: ${g(e)}`),e.dataset.iframeSize=!0})))}function je(e){({add(t){function n(){Qe(e.eventName,e.eventType)}h[t]=n,a(window,t,n,{passive:!0})},remove(e){const t=h[e];var n,o;delete h[e],n=e,o=t,window.removeEventListener(n,o,!1)}})[e.method](e.eventName),v(`${p(e.method)} event listener: ${e.eventType}`)}function Pe(e){je({method:e,eventType:"After Print",eventName:"afterprint"}),je({method:e,eventType:"Before Print",eventName:"beforeprint"}),je({method:e,eventType:"Ready State Change",eventName:"readystatechange"})}function Te(e,t,n,o){return t!==e&&(e in n||(z(`${e} is not a valid option for ${o}CalculationMethod.`),e=t),e in u&&w(`<rb>Deprecated ${o}CalculationMethod (${e})</>\n\nThis version of <i>iframe-resizer</> can auto detect the most suitable ${o} calculation method. It is recommended that you remove this option.`),v(`${o} calculation method set to "${e}"`)),e}function Ce(){Q=Te(Q,b,Ve,"height")}function Oe(){pe=Te(pe,k,Je,"width")}function Ae(){!0===L?(Pe("add"),W=function(){const e=new Set;let t=!1,n=[];const o=t=>e.add(t),i=t=>e.delete(t),r=e=>{const{length:t}=e;for(let n=0;n<t;n++)e[n].addedNodes.forEach(o),e[n].removedNodes.forEach(i);n=[]};function a(){n.forEach(r),0!==e.size&&(Me(),$e(),Se(e),e.forEach(qe),e.clear(),t=!1)}function l(e){n.push(e),t||(t=!0,requestAnimationFrame(a))}function s(){const e=new window.MutationObserver(l),t=document.querySelector("body"),n={attributes:!1,attributeOldValue:!1,characterData:!1,characterDataOldValue:!1,childList:!0,subtree:!0};return v("Create <body/> MutationObserver"),e.observe(t,n),e}const c=s();return{disconnect(){v("Disconnect MutationObserver"),c.disconnect()}}}(),ie=new ResizeObserver(ke),qe(window.document)):v("Auto Resize disabled")}let Ie;function ke(e){if(!Array.isArray(e)||0===e.length)return;const t=e[0].target;Ie=()=>Qe("resizeObserver",`Resize Observed: ${g(t)}`),setTimeout((()=>{Ie&&Ie(),Ie=void 0}),0)}const Re=e=>{const t=getComputedStyle(e);return""!==t?.position&&"static"!==t?.position},Ne=()=>[...We(document)()].filter(Re),xe=new WeakSet;function Le(e){e&&(xe.has(e)||(ie.observe(e),xe.add(e),v(`Attached resizeObserver: ${g(e)}`)))}function qe(e){[...Ne(),...I.flatMap((t=>e.querySelector(t)))].forEach(Le)}function Be(e){performance.mark(P);const t=p(e);let n=0,i=document.documentElement,r=J?0:document.documentElement.getBoundingClientRect().bottom;performance.mark(P);const a=J?le:M()?S:We(document)();let l=a.length;return a.forEach((t=>{J||!y||t.checkVisibility(o)?(n=t.getBoundingClientRect()[e]+parseFloat(getComputedStyle(t).getPropertyValue(`margin-${e}`)),n>r&&(r=n,i=t)):l-=1})),N=i,performance.mark(T,{detail:{Side:t,len:l,hasTags:J,logging:K}}),r}const Fe=e=>[e.bodyOffset(),e.bodyScroll(),e.documentElementOffset(),e.documentElementScroll(),e.documentElementBoundingClientRect()],We=e=>()=>e.querySelectorAll("* :not(head):not(meta):not(base):not(title):not(script):not(link):not(style):not(map):not(area):not(option):not(optgroup):not(template):not(track):not(wbr):not(nobr)"),De={height:0,width:0},He={height:0,width:0};function Ue(e){function t(){return He[i]=r,De[i]=s,r}const n=M(),o=e===Ve,i=o?"height":"width",r=e.documentElementBoundingClientRect(),a=Math.ceil(r),l=Math.floor(r),s=(e=>e.documentElementScroll()+Math.max(0,e.getOffset()))(e),c=`HTML: ${r} Page: ${s}`;switch(!0){case!e.enabled():return s;case J:return e.taggedElement();case!n&&0===He[i]&&0===De[i]:return v(`Initial page size values: ${c}`),t();case ue&&r===He[i]&&s===De[i]:return v(`Size unchanged: ${c}`),Math.max(r,s);case 0===r:return v(`Page is hidden: ${c}`),s;case!n&&r!==He[i]&&s<=De[i]:return v(`New HTML bounding size: ${c}`,"Previous bounding size:",He[i]),t();case!o:return e.taggedElement();case!n&&r<He[i]:return v("HTML bounding size decreased:",c),t();case s===l||s===a:return v("HTML bounding size equals page size:",c),t();case r>s:return v(`Page size < HTML bounding size: ${c}`),t();default:v(`Content overflowing HTML element: ${c}`)}return Math.max(e.taggedElement(),t())}const Ve={enabled:()=>H,getOffset:()=>R,auto:()=>Ue(Ve),bodyOffset:()=>{const{body:e}=document,n=getComputedStyle(e);return e.offsetHeight+parseInt(n.marginTop,t)+parseInt(n.marginBottom,t)},bodyScroll:()=>document.body.scrollHeight,offset:()=>Ve.bodyOffset(),custom:()=>l.height(),documentElementOffset:()=>document.documentElement.offsetHeight,documentElementScroll:()=>document.documentElement.scrollHeight,documentElementBoundingClientRect:()=>document.documentElement.getBoundingClientRect().bottom,max:()=>Math.max(...Fe(Ve)),min:()=>Math.min(...Fe(Ve)),grow:()=>Ve.max(),lowestElement:()=>Be(i),taggedElement:()=>Be(i)},Je={enabled:()=>U,getOffset:()=>x,auto:()=>Ue(Je),bodyScroll:()=>document.body.scrollWidth,bodyOffset:()=>document.body.offsetWidth,custom:()=>l.width(),documentElementScroll:()=>document.documentElement.scrollWidth,documentElementOffset:()=>document.documentElement.offsetWidth,documentElementBoundingClientRect:()=>document.documentElement.getBoundingClientRect().right,max:()=>Math.max(...Fe(Je)),min:()=>Math.min(...Fe(Je)),rightMostElement:()=>Be(r),scroll:()=>Math.max(Je.bodyScroll(),Je.documentElementScroll()),taggedElement:()=>Be(r)};function Ze(e,t,n,o,i){let r,a;!function(){const e=(e,t)=>!(Math.abs(e-t)<=de);return r=void 0===n?Ve[Q]():n,a=void 0===o?Je[pe]():o,H&&e(Z,r)||U&&e(fe,a)}()&&"init"!==e?!(e in{init:1,size:1})&&(H&&Q in A||U&&pe in A)&&Ge(t):(Xe(),Z=r,fe=a,Ke(Z,fe,e,i))}function Qe(e,t,n,o,i){document.hidden?v("Page hidden - Ignored resize request"):(e in j||v(`Trigger event: ${t}`),Ze(e,t,n,o,i))}function Xe(){ue||(ue=!0,v("Trigger event lock on"),requestAnimationFrame((()=>{ue=!1,v("Trigger event lock off"),v("--")})))}function Ye(e){Z=Ve[Q](),fe=Je[pe](),Ke(Z,fe,e)}function Ge(e){const t=Q;Q=b,v(`Reset trigger event: ${e}`),Xe(),Ye("reset"),Q=t}function Ke(e,t,n,o,i){_<-1||(void 0!==i?v(`Message targetOrigin: ${i}`):i=ce,function(){const r=`${te}:${e+(R||0)}:${t+(x||0)}:${n}${void 0===o?"":`:${o}`}`;v(`Sending message to host page (${r}) via ${re?"sameDomain":"postMessage"}`),re?window.parent.iframeParentListener(C+r):se.postMessage(C+r,i)}())}function _e(e){const t={init:function(){Y=e.data,se=e.source,ze(),V=!1,setTimeout((()=>{X=!1}),m)},reset(){X?v("Page reset ignored by init"):(v("Page size reset by host page"),Ye("resetPage"))},resize(){Qe("resizeParent","Parent window requested size check")},moveToAnchor(){G.findTarget(o())},inPageLink(){this.moveToAnchor()},pageInfo(){const e=o();v(`PageInfo received from parent: ${e}`),ve?ve(JSON.parse(e)):Ke(0,0,"pageInfoStop"),v(" --")},parentInfo(){const e=o();v(`ParentInfo received from parent: ${e}`),be?be(Object.freeze(JSON.parse(e))):Ke(0,0,"parentInfoStop"),v(" --")},message(){const e=o();v(`onMessage called from parent: ${e}`),ge(JSON.parse(e)),v(" --")}},n=()=>e.data.split("]")[1].split(":")[0],o=()=>e.data.slice(e.data.indexOf(":")+1),i=()=>"iframeResize"in window||void 0!==window.jQuery&&""in window.jQuery.prototype,r=()=>e.data.split(":")[2]in{true:1,false:1};C===`${e.data}`.slice(0,O)&&(!1!==V?r()?t.init():v(`Ignored message of type "${n()}". Received before initialization.`):function(){const o=n();o in t?t[o]():i()||r()||z(`Unexpected message (${e.data})`)}())}function et(){"loading"!==document.readyState&&window.parent.postMessage("[iFrameResizerChild]Ready","*")}window.iframeChildListener=e=>_e({data:e,sameDomain:!0}),a(window,"message",_e),a(window,"readystatechange",et),et()}();
21
- //# sourceMappingURL=index.cjs.js.map
20
+ 'use strict';
21
+
22
+ const VERSION = '5.2.2-beta.3';
23
+
24
+ const BASE = 10;
25
+
26
+ const SIZE_ATTR = 'data-iframe-size';
27
+ const OVERFLOW_ATTR = 'data-iframe-overflow';
28
+
29
+ const HEIGHT_EDGE = 'bottom';
30
+ const WIDTH_EDGE = 'right';
31
+
32
+ const addEventListener = (el, evt, func, options) =>
33
+ el.addEventListener(evt, func, options || false);
34
+
35
+ const removeEventListener = (el, evt, func) =>
36
+ el.removeEventListener(evt, func, false);
37
+
38
+ const p = (l) =>
39
+ l.replaceAll(/[A-Za-z]/g, (l) =>
40
+ String.fromCodePoint(
41
+ (l <= 'Z' ? 90 : 122) >= (l = l.codePointAt(0) + 19) ? l : l - 26,
42
+ ),
43
+ ),
44
+ y = [
45
+ '<iy><yi>Puchspk Spjluzl Rlf</><iy><iy>',
46
+ '<iy><yi>Tpzzpun Spjluzl Rlf</><iy><iy>',
47
+ 'Aopz spiyhyf pz hchpshisl dpao ivao Jvttlyjphs huk Vwlu-Zvbyjl spjluzlz.<iy><iy><i>Jvttlyjphs Spjluzl</><iy>Mvy jvttlyjphs bzl, <p>pmyhtl-ylzpgly</> ylxbpylz h svd jvza vul aptl spjluzl mll. Mvy tvyl pumvythapvu cpzpa <b>oaawz://pmyhtl-ylzpgly.jvt/wypjpun</>.<iy><iy><i>Vwlu Zvbyjl Spjluzl</><iy>Pm fvb hyl bzpun aopz spiyhyf pu h uvu-jvttlyjphs vwlu zvbyjl wyvqlja aolu fvb jhu bzl pa mvy myll bukly aol alytz vm aol NWS C3 Spjluzl. Av jvumpyt fvb hjjlwa aolzl alytz, wslhzl zla aol <i>spjluzl</> rlf pu <p>pmyhtl-ylzpgly</> vwapvuz av <i>NWSc3</>.<iy><iy>Mvy tvyl pumvythapvu wslhzl zll: <b>oaawz://pmyhtl-ylzpgly.jvt/nws</>',
48
+ '<i>NWSc3 Spjluzl Clyzpvu</><iy><iy>Aopz clyzpvu vm <p>pmyhtl-ylzpgly</> pz ilpun bzlk bukly aol alytz vm aol <i>NWS C3</> spjluzl. Aopz spjluzl hssvdz fvb av bzl <p>pmyhtl-ylzpgly</> pu Vwlu Zvbyjl wyvqljaz, iba pa ylxbpylz fvby wyvqlja av il wbispj, wyvcpkl haaypibapvu huk il spjluzlk bukly clyzpvu 3 vy shaly vm aol NUB Nlulyhs Wbispj Spjluzl.<iy><iy>Pm fvb hyl bzpun aopz spiyhyf pu h uvu-vwlu zvbyjl wyvqlja vy dlizpal, fvb dpss ullk av wbyjohzl h svd jvza vul aptl jvttlyjphs spjluzl.<iy><iy>Mvy tvyl pumvythapvu cpzpa <b>oaawz://pmyhtl-ylzpgly.jvt/wypjpun</>.',
49
+ ];
50
+ Object.fromEntries(
51
+ [
52
+ '2cgs7fdf4xb',
53
+ '1c9ctcccr4z',
54
+ '1q2pc4eebgb',
55
+ 'ueokt0969w',
56
+ 'w2zxchhgqz',
57
+ '1umuxblj2e5',
58
+ ].map((l, p) => [l, Math.max(0, p - 1)]),
59
+ );
60
+ const getModeData = (l) => p(y[l]);
61
+
62
+ const once = (fn) => {
63
+ let done = false;
64
+
65
+ return function () {
66
+ return done
67
+ ? undefined
68
+ : ((done = true), Reflect.apply(fn, this, arguments))
69
+ }
70
+ };
71
+
72
+ const id$1 = (x) => x;
73
+
74
+ const encode = (s) =>
75
+ s
76
+ .replaceAll('<br>', '\n')
77
+ .replaceAll('<rb>', '\u001B[31;1m')
78
+ .replaceAll('</>', '\u001B[m')
79
+ .replaceAll('<b>', '\u001B[1m')
80
+ .replaceAll('<i>', '\u001B[3m')
81
+ .replaceAll('<u>', '\u001B[4m');
82
+
83
+ const remove = (s) => s.replaceAll('<br>', '\n').replaceAll(/<[/a-z]+>/gi, '');
84
+
85
+ const formatAdvise = (formatLogMsg) => (msg) =>
86
+ window.chrome // Only show formatting in Chrome as not supported in other browsers
87
+ ? formatLogMsg(encode(msg))
88
+ : formatLogMsg(remove(msg));
89
+
90
+ let id = '';
91
+ let logging = false;
92
+
93
+ const setLogOptions = (options) => {
94
+ id = options.id;
95
+ logging = options.logging;
96
+ };
97
+
98
+ const capitalizeFirstLetter = (string) =>
99
+ string.charAt(0).toUpperCase() + string.slice(1);
100
+
101
+ const isDef = (value) => `${value}` !== '' && value !== undefined;
102
+
103
+ function getElementName(el) {
104
+ switch (true) {
105
+ case !isDef(el):
106
+ return ''
107
+
108
+ case isDef(el.id):
109
+ return `${el.nodeName.toUpperCase()}#${el.id}`
110
+
111
+ case isDef(el.name):
112
+ return `${el.nodeName.toUpperCase()} (${el.name})`
113
+
114
+ default:
115
+ return (
116
+ el.nodeName.toUpperCase() +
117
+ (isDef(el.className) ? `.${el.className}` : '')
118
+ )
119
+ }
120
+ }
121
+
122
+ // function elementSnippet(el, maxChars = 30) {
123
+ // const outer = el?.outerHTML?.toString()
124
+
125
+ // if (!outer) return el
126
+
127
+ // return outer.length < maxChars
128
+ // ? outer
129
+ // : `${outer.slice(0, maxChars).replaceAll('\n', ' ')}...`
130
+ // }
131
+
132
+ // TODO: remove .join(' '), requires major test updates
133
+ const formatLogMsg = (...msg) => [`[iframe-resizer][${id}]`, ...msg].join(' ');
134
+
135
+ const log = (...msg) =>
136
+ // eslint-disable-next-line no-console
137
+ logging && console?.log(formatLogMsg(...msg));
138
+
139
+ // eslint-disable-next-line no-unused-vars
140
+ const info = (...msg) =>
141
+ // eslint-disable-next-line no-console
142
+ console?.info(`[iframe-resizer][${id}]`, ...msg);
143
+
144
+ const warn = (...msg) =>
145
+ // eslint-disable-next-line no-console
146
+ console?.warn(formatLogMsg(...msg));
147
+
148
+ const advise = (...msg) =>
149
+ // eslint-disable-next-line no-console
150
+ console?.warn(formatAdvise(formatLogMsg)(...msg));
151
+
152
+ const adviser = (msg) => advise(msg);
153
+
154
+ let overflowedElements = [];
155
+
156
+ const overflowObserver = (options) => {
157
+ const side = options.side || HEIGHT_EDGE;
158
+ const onChange = options.onChange || id$1;
159
+
160
+ const observerOptions = {
161
+ root: document.documentElement,
162
+ rootMargin: '0px',
163
+ threshold: 1,
164
+ };
165
+
166
+ const observedElements = new WeakSet();
167
+
168
+ const isTarget = (entry) =>
169
+ entry.boundingClientRect[side] === 0 ||
170
+ entry.boundingClientRect[side] > entry.rootBounds[side];
171
+
172
+ const callback = (entries) => {
173
+ entries.forEach((entry) => {
174
+ entry.target.toggleAttribute(OVERFLOW_ATTR, isTarget(entry));
175
+ });
176
+
177
+ overflowedElements = document.querySelectorAll(`[${OVERFLOW_ATTR}]`);
178
+ log('overflowedElements:', overflowedElements);
179
+ onChange();
180
+ };
181
+
182
+ const observer = new IntersectionObserver(callback, observerOptions);
183
+
184
+ return (nodeList) =>
185
+ nodeList.forEach((el) => {
186
+ if (observedElements.has(el)) return
187
+ observer.observe(el);
188
+ observedElements.add(el);
189
+ })
190
+ };
191
+
192
+ const isOverflowed = () => overflowedElements.length > 0;
193
+ const getOverflowedElements = () => overflowedElements;
194
+
195
+ const SECOND = 1000;
196
+ const DEC_PLACES = 100_000; // 5 decimal places
197
+ const PERF_CHECK_INTERVAL = 5 * SECOND;
198
+ const THRESHOLD = 4; // ms
199
+
200
+ const PREF_START = '--ifr-start';
201
+ const PREF_END = '--ifr-end';
202
+ const PREF_MEASURE = '--ifr-measure';
203
+
204
+ const timings = [];
205
+ const usedTags = new WeakSet();
206
+
207
+ const addUsedTag = (el) => typeof el === 'object' && usedTags.add(el);
208
+ const round = (num) => Math.floor(num * DEC_PLACES) / DEC_PLACES;
209
+
210
+ let lastPerfEl = null;
211
+ let perfEl = null;
212
+ let details = {};
213
+
214
+ const setPerfEl = (el) => {
215
+ perfEl = el;
216
+ };
217
+
218
+ function usedEl(detail, duration) {
219
+ // eslint-disable-next-line no-unused-vars
220
+ const { Side, len, hasTags, logging } = detail;
221
+
222
+ details = detail;
223
+
224
+ if (usedTags.has(perfEl) || lastPerfEl === perfEl || (hasTags && len <= 1)) {
225
+ return
226
+ }
227
+
228
+ if (!logging) addUsedTag(perfEl);
229
+
230
+ lastPerfEl = perfEl;
231
+
232
+ info(
233
+ `\n${Side} position calculated from:\n`,
234
+ perfEl,
235
+ `\nParsed ${len} ${hasTags ? 'tagged' : 'potentially overflowing'} elements in ${round(duration)}ms`,
236
+ );
237
+ }
238
+
239
+ const timingCheck = setInterval(() => {
240
+ if (timings.length < 10) return
241
+ if (details.hasTags && details.len < 25) return
242
+
243
+ timings.sort();
244
+
245
+ const average = Math.min(
246
+ timings.reduce((a, b) => a + b, 0) / timings.length,
247
+ timings[Math.floor(timings.length / 2)],
248
+ );
249
+
250
+ // console.info('Timings:', JSON.parse(JSON.stringify(timings)))
251
+ // console.info('Mean time:', timings[Math.floor(timings.length / 2)])
252
+ // console.info(
253
+ // 'Median time:',
254
+ // timings.reduce((a, b) => a + b, 0) / timings.length,
255
+ // )
256
+ // console.info('Average time:', round(average), average)
257
+
258
+ log('Max time:', Math.max(...timings));
259
+
260
+ if (average <= THRESHOLD) return
261
+
262
+ clearInterval(timingCheck);
263
+
264
+ advise(
265
+ `<rb>Performance Warning</>
266
+
267
+ Calculating the page size is taking an excessive amount of time (${round(average)}ms).
268
+
269
+ To improve performance add the <b>data-iframe-size</> attribute to the ${details.Side.toLowerCase()} most element on the page. For more details see: <u>https://iframe-resizer.com/perf</>.`,
270
+ );
271
+ }, PERF_CHECK_INTERVAL);
272
+
273
+ function perfObserver(list) {
274
+ list.getEntries().forEach((entry) => {
275
+ if (entry.name === PREF_END) {
276
+ const { duration } = performance.measure(
277
+ PREF_MEASURE,
278
+ PREF_START,
279
+ PREF_END,
280
+ );
281
+ usedEl(entry.detail, duration);
282
+ timings.push(duration);
283
+ if (timings.length > 100) timings.shift();
284
+ }
285
+ });
286
+ }
287
+
288
+ function setup() {
289
+ const observer = new PerformanceObserver(perfObserver);
290
+ observer.observe({ entryTypes: ['mark'] });
291
+
292
+ addUsedTag(document.documentElement);
293
+ addUsedTag(document.body);
294
+ }
295
+
296
+ if (
297
+ // Guard against everything, as we don't control where and when we are loaded
298
+ typeof document !== 'undefined' &&
299
+ typeof PerformanceObserver !== 'undefined'
300
+ ) {
301
+ if (document.readyState === 'loading') {
302
+ document.addEventListener('DOMContentLoaded', setup);
303
+ } else {
304
+ setup();
305
+ }
306
+ }
307
+
308
+ function iframeResizerChild() {
309
+ const checkVisibilityOptions = {
310
+ contentVisibilityAuto: true,
311
+ opacityProperty: true,
312
+ visibilityProperty: true,
313
+ };
314
+ const customCalcMethods = {
315
+ height: () => {
316
+ warn('Custom height calculation function not defined');
317
+ return getHeight.auto()
318
+ },
319
+ width: () => {
320
+ warn('Custom width calculation function not defined');
321
+ return getWidth.auto()
322
+ },
323
+ };
324
+ const deprecatedResizeMethods = {
325
+ bodyOffset: 1,
326
+ bodyScroll: 1,
327
+ offset: 1,
328
+ documentElementOffset: 1,
329
+ documentElementScroll: 1,
330
+ documentElementBoundingClientRect: 1,
331
+ max: 1,
332
+ min: 1,
333
+ grow: 1,
334
+ lowestElement: 1,
335
+ };
336
+ const eventCancelTimer = 128;
337
+ const eventHandlersByName = {};
338
+ const hasCheckVisibility = 'checkVisibility' in window;
339
+ const heightCalcModeDefault = 'auto';
340
+ // const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent)
341
+ const nonLoggableTriggerEvents = { reset: 1, resetPage: 1, init: 1 };
342
+ const msgID = '[iFrameSizer]'; // Must match host page msg ID
343
+ const msgIdLen = msgID.length;
344
+ const resetRequiredMethods = {
345
+ max: 1,
346
+ min: 1,
347
+ bodyScroll: 1,
348
+ documentElementScroll: 1,
349
+ };
350
+ const resizeObserveTargets = ['body'];
351
+ const widthCalcModeDefault = 'scroll';
352
+
353
+ let autoResize = true;
354
+ let bodyBackground = '';
355
+ let bodyMargin = 0;
356
+ let bodyMarginStr = '';
357
+ let bodyObserver = null;
358
+ let bodyPadding = '';
359
+ let calculateHeight = true;
360
+ let calculateWidth = false;
361
+ let firstRun = true;
362
+ let hasTags = false;
363
+ let height = 1;
364
+ let heightCalcMode = heightCalcModeDefault; // only applies if not provided by host page (V1 compatibility)
365
+ let initLock = true;
366
+ let initMsg = '';
367
+ let inPageLinks = {};
368
+ let logging = false;
369
+ let mode = 0;
370
+ let mouseEvents = false;
371
+ let myID = '';
372
+ let offsetHeight;
373
+ let offsetWidth;
374
+ let observeOverflow = id$1;
375
+ let resizeFrom = 'child';
376
+ let resizeObserver = null;
377
+ let sameDomain = false;
378
+ let sizeSelector = '';
379
+ let taggedElements = [];
380
+ let target = window.parent;
381
+ let targetOriginDefault = '*';
382
+ let tolerance = 0;
383
+ let triggerLocked = false;
384
+ let version = '';
385
+ let width = 1;
386
+ let widthCalcMode = widthCalcModeDefault;
387
+ let win = window;
388
+
389
+ let onMessage = () => {
390
+ warn('onMessage function not defined');
391
+ };
392
+ let onReady = () => {};
393
+ let onPageInfo = null;
394
+ let onParentInfo = null;
395
+
396
+ function init() {
397
+ readDataFromParent();
398
+ readDataFromPage();
399
+
400
+ log(`Initialising iFrame v${VERSION} (${window.location.href})`);
401
+
402
+ setLogOptions({ id: myID, logging });
403
+
404
+ checkCrossDomain();
405
+ checkMode();
406
+ checkVersion();
407
+ checkHeightMode();
408
+ checkWidthMode();
409
+ checkDeprecatedAttrs();
410
+
411
+ checkAndSetupTags();
412
+
413
+ setupObserveOverflow();
414
+ setupPublicMethods();
415
+ setupMouseEvents();
416
+ inPageLinks = setupInPageLinks();
417
+
418
+ addOverflowObservers(getAllElements(document)());
419
+
420
+ setMargin();
421
+ setBodyStyle('background', bodyBackground);
422
+ setBodyStyle('padding', bodyPadding);
423
+
424
+ injectClearFixIntoBodyElement();
425
+ stopInfiniteResizingOfIFrame();
426
+ applySizeSelector();
427
+ }
428
+
429
+ // Continue init after intersection observer has been setup
430
+ const initContinue = () => {
431
+ sendSize(
432
+ 'init',
433
+ 'Init message from host page',
434
+ undefined,
435
+ undefined,
436
+ VERSION,
437
+ );
438
+ sendTitle();
439
+ initEventListeners();
440
+ onReady();
441
+
442
+ log('Initialization complete');
443
+ log('---');
444
+ };
445
+
446
+ function setupObserveOverflow() {
447
+ if (calculateHeight === calculateWidth) return
448
+ observeOverflow = overflowObserver({
449
+ onChange: once(initContinue),
450
+ side: calculateHeight ? HEIGHT_EDGE : WIDTH_EDGE,
451
+ });
452
+ }
453
+
454
+ function checkAndSetupTags() {
455
+ taggedElements = document.querySelectorAll(`[${SIZE_ATTR}]`);
456
+ hasTags = taggedElements.length > 0;
457
+ log(`Tagged elements found: ${hasTags}`);
458
+ }
459
+
460
+ function addOverflowObservers(nodeList) {
461
+ if (hasTags) setTimeout(initContinue);
462
+ else observeOverflow(nodeList);
463
+ }
464
+
465
+ function sendTitle() {
466
+ if (document.title && document.title !== '') {
467
+ sendMsg(0, 0, 'title', document.title);
468
+ }
469
+ }
470
+
471
+ function checkVersion() {
472
+ if (!version || version === '' || version === 'false') {
473
+ advise(
474
+ `<rb>Legacy version detected on parent page</>
475
+
476
+ Detected legacy version of parent page script. It is recommended to update the parent page to use <b>@iframe-resizer/parent</>.
477
+
478
+ See <u>https://iframe-resizer.com/setup/</> for more details.
479
+ `,
480
+ );
481
+ return
482
+ }
483
+
484
+ if (version !== VERSION) {
485
+ advise(
486
+ `<rb>Version mismatch</>
487
+
488
+ The parent and child pages are running different versions of <i>iframe resizer</>.
489
+
490
+ Parent page: ${version} - Child page: ${VERSION}.
491
+ `,
492
+ );
493
+ }
494
+ }
495
+
496
+ function checkCrossDomain() {
497
+ try {
498
+ sameDomain = 'iframeParentListener' in window.parent;
499
+ } catch (error) {
500
+ log('Cross domain iframe detected.');
501
+ }
502
+ }
503
+
504
+ // eslint-disable-next-line sonarjs/cognitive-complexity
505
+ function readDataFromParent() {
506
+ const strBool = (str) => str === 'true';
507
+ const data = initMsg.slice(msgIdLen).split(':');
508
+
509
+ myID = data[0]; // eslint-disable-line prefer-destructuring
510
+ bodyMargin = undefined === data[1] ? bodyMargin : Number(data[1]); // For V1 compatibility
511
+ calculateWidth = undefined === data[2] ? calculateWidth : strBool(data[2]);
512
+ logging = undefined === data[3] ? logging : strBool(data[3]);
513
+ // data[4] no longer used (was intervalTimer)
514
+ autoResize = undefined === data[6] ? autoResize : strBool(data[6]);
515
+ bodyMarginStr = data[7]; // eslint-disable-line prefer-destructuring
516
+ heightCalcMode = undefined === data[8] ? heightCalcMode : data[8];
517
+ bodyBackground = data[9]; // eslint-disable-line prefer-destructuring
518
+ bodyPadding = data[10]; // eslint-disable-line prefer-destructuring
519
+ tolerance = undefined === data[11] ? tolerance : Number(data[11]);
520
+ inPageLinks.enable = undefined === data[12] ? false : strBool(data[12]);
521
+ resizeFrom = undefined === data[13] ? resizeFrom : data[13];
522
+ widthCalcMode = undefined === data[14] ? widthCalcMode : data[14];
523
+ mouseEvents = undefined === data[15] ? mouseEvents : strBool(data[15]);
524
+ offsetHeight = undefined === data[16] ? offsetHeight : Number(data[16]);
525
+ offsetWidth = undefined === data[17] ? offsetWidth : Number(data[17]);
526
+ calculateHeight =
527
+ undefined === data[18] ? calculateHeight : strBool(data[18]);
528
+ data[19]; // eslint-disable-line prefer-destructuring
529
+ version = data[20] || version;
530
+ mode = undefined === data[21] ? mode : Number(data[21]);
531
+ // sizeSelector = data[22] || sizeSelector
532
+ }
533
+
534
+ function readDataFromPage() {
535
+ // eslint-disable-next-line sonarjs/cognitive-complexity
536
+ function readData() {
537
+ const data = window.iframeResizer || window.iFrameResizer;
538
+
539
+ log(`Reading data from page: ${JSON.stringify(data)}`);
540
+
541
+ onMessage = data?.onMessage || onMessage;
542
+ onReady = data?.onReady || onReady;
543
+
544
+ if (typeof data?.offset === 'number') {
545
+ advise(
546
+ `<rb>Deprecated option</>\n\n The <b>offset</> option has been renamed to <b>offsetSize</>. Use of the old name will be removed in a future version of <i>iframe-resizer</>.`,
547
+ );
548
+ if (calculateHeight) offsetHeight = data?.offset;
549
+ if (calculateWidth) offsetWidth = data?.offset;
550
+ }
551
+
552
+ if (typeof data?.offsetSize === 'number') {
553
+ if (calculateHeight) offsetHeight = data?.offsetSize;
554
+ if (calculateWidth) offsetWidth = data?.offsetSize;
555
+ }
556
+
557
+ if (Object.prototype.hasOwnProperty.call(data, 'sizeSelector')) {
558
+ sizeSelector = data.sizeSelector;
559
+ }
560
+
561
+ targetOriginDefault = data?.targetOrigin || targetOriginDefault;
562
+ heightCalcMode = data?.heightCalculationMethod || heightCalcMode;
563
+ widthCalcMode = data?.widthCalculationMethod || widthCalcMode;
564
+ }
565
+
566
+ function setupCustomCalcMethods(calcMode, calcFunc) {
567
+ if (typeof calcMode === 'function') {
568
+ log(`Setup custom ${calcFunc}CalcMethod`);
569
+ customCalcMethods[calcFunc] = calcMode;
570
+ calcMode = 'custom';
571
+ }
572
+
573
+ return calcMode
574
+ }
575
+
576
+ if (mode === 1) return
577
+
578
+ if (
579
+ 'iFrameResizer' in window &&
580
+ Object === window.iFrameResizer.constructor
581
+ ) {
582
+ readData();
583
+ heightCalcMode = setupCustomCalcMethods(heightCalcMode, 'height');
584
+ widthCalcMode = setupCustomCalcMethods(widthCalcMode, 'width');
585
+ }
586
+
587
+ log(`TargetOrigin for parent set to: ${targetOriginDefault}`);
588
+ }
589
+
590
+ function chkCSS(attr, value) {
591
+ if (value.includes('-')) {
592
+ warn(`Negative CSS value ignored for ${attr}`);
593
+ value = '';
594
+ }
595
+
596
+ return value
597
+ }
598
+
599
+ function setBodyStyle(attr, value) {
600
+ if (undefined !== value && value !== '' && value !== 'null') {
601
+ document.body.style.setProperty(attr, value);
602
+ log(`Body ${attr} set to "${value}"`);
603
+ }
604
+ }
605
+
606
+ function applySizeSelector() {
607
+ if (sizeSelector === '') return
608
+
609
+ log(`Applying sizeSelector: ${sizeSelector}`);
610
+
611
+ document.querySelectorAll(sizeSelector).forEach((el) => {
612
+ log(`Applying data-iframe-size to: ${getElementName(el)}`);
613
+ el.dataset.iframeSize = true;
614
+ });
615
+ }
616
+
617
+ function setMargin() {
618
+ // If called via V1 script, convert bodyMargin from int to str
619
+ if (undefined === bodyMarginStr) {
620
+ bodyMarginStr = `${bodyMargin}px`;
621
+ }
622
+
623
+ setBodyStyle('margin', chkCSS('margin', bodyMarginStr));
624
+ }
625
+
626
+ function stopInfiniteResizingOfIFrame() {
627
+ const setAutoHeight = (el) =>
628
+ el.style.setProperty('height', 'auto', 'important');
629
+
630
+ setAutoHeight(document.documentElement);
631
+ setAutoHeight(document.body);
632
+
633
+ log('HTML & body height set to "auto !important"');
634
+ }
635
+
636
+ function manageTriggerEvent(options) {
637
+ const listener = {
638
+ add(eventName) {
639
+ function handleEvent() {
640
+ sendSize(options.eventName, options.eventType);
641
+ }
642
+
643
+ eventHandlersByName[eventName] = handleEvent;
644
+
645
+ addEventListener(window, eventName, handleEvent, { passive: true });
646
+ },
647
+ remove(eventName) {
648
+ const handleEvent = eventHandlersByName[eventName];
649
+ delete eventHandlersByName[eventName];
650
+
651
+ removeEventListener(window, eventName, handleEvent);
652
+ },
653
+ };
654
+
655
+ listener[options.method](options.eventName);
656
+
657
+ log(
658
+ `${capitalizeFirstLetter(options.method)} event listener: ${
659
+ options.eventType
660
+ }`,
661
+ );
662
+ }
663
+
664
+ function manageEventListeners(method) {
665
+ manageTriggerEvent({
666
+ method,
667
+ eventType: 'After Print',
668
+ eventName: 'afterprint',
669
+ });
670
+
671
+ manageTriggerEvent({
672
+ method,
673
+ eventType: 'Before Print',
674
+ eventName: 'beforeprint',
675
+ });
676
+
677
+ manageTriggerEvent({
678
+ method,
679
+ eventType: 'Ready State Change',
680
+ eventName: 'readystatechange',
681
+ });
682
+ }
683
+
684
+ function checkDeprecatedAttrs() {
685
+ let found = false;
686
+
687
+ const checkAttrs = (attr) =>
688
+ document.querySelectorAll(`[${attr}]`).forEach((el) => {
689
+ found = true;
690
+ el.removeAttribute(attr);
691
+ el.toggleAttribute(SIZE_ATTR, true);
692
+ });
693
+
694
+ checkAttrs('data-iframe-height');
695
+ checkAttrs('data-iframe-width');
696
+
697
+ if (found) {
698
+ advise(
699
+ `<rb>Deprecated Attributes</>
700
+
701
+ The <b>data-iframe-height</> and <b>data-iframe-width</> attributes have been deprecated and replaced with the single <b>data-iframe-size</> attribute. Use of the old attributes will be removed in a future version of <i>iframe-resizer</>.`,
702
+ );
703
+ }
704
+ }
705
+
706
+ function checkCalcMode(calcMode, calcModeDefault, modes, type) {
707
+ if (calcModeDefault !== calcMode) {
708
+ if (!(calcMode in modes)) {
709
+ warn(`${calcMode} is not a valid option for ${type}CalculationMethod.`);
710
+ calcMode = calcModeDefault;
711
+ }
712
+ if (calcMode in deprecatedResizeMethods) {
713
+ advise(
714
+ `<rb>Deprecated ${type}CalculationMethod (${calcMode})</>
715
+
716
+ This version of <i>iframe-resizer</> can auto detect the most suitable ${type} calculation method. It is recommended that you remove this option.`,
717
+ );
718
+ }
719
+ log(`${type} calculation method set to "${calcMode}"`);
720
+ }
721
+
722
+ return calcMode
723
+ }
724
+
725
+ function checkHeightMode() {
726
+ heightCalcMode = checkCalcMode(
727
+ heightCalcMode,
728
+ heightCalcModeDefault,
729
+ getHeight,
730
+ 'height',
731
+ );
732
+ }
733
+
734
+ function checkWidthMode() {
735
+ widthCalcMode = checkCalcMode(
736
+ widthCalcMode,
737
+ widthCalcModeDefault,
738
+ getWidth,
739
+ 'width',
740
+ );
741
+ }
742
+
743
+ function checkMode() {
744
+ if (mode < 0) return adviser(`${getModeData(mode + 2)}${getModeData(2)}`)
745
+ if (version.codePointAt(0) > 4) return mode
746
+ if (mode < 2) return adviser(getModeData(3))
747
+ return mode
748
+ }
749
+
750
+ function initEventListeners() {
751
+ if (autoResize !== true) {
752
+ log('Auto Resize disabled');
753
+ return
754
+ }
755
+
756
+ manageEventListeners('add');
757
+ setupMutationObserver();
758
+ setupResizeObserver();
759
+ }
760
+
761
+ function stopEventListeners() {
762
+ manageEventListeners('remove');
763
+ resizeObserver?.disconnect();
764
+ bodyObserver?.disconnect();
765
+ }
766
+
767
+ function injectClearFixIntoBodyElement() {
768
+ const clearFix = document.createElement('div');
769
+
770
+ clearFix.style.clear = 'both';
771
+ // Guard against the following having been globally redefined in CSS.
772
+ clearFix.style.display = 'block';
773
+ clearFix.style.height = '0';
774
+ document.body.append(clearFix);
775
+ }
776
+
777
+ function setupInPageLinks() {
778
+ const getPagePosition = () => ({
779
+ x: document.documentElement.scrollLeft,
780
+ y: document.documentElement.scrollTop,
781
+ });
782
+
783
+ function getElementPosition(el) {
784
+ const elPosition = el.getBoundingClientRect();
785
+ const pagePosition = getPagePosition();
786
+
787
+ return {
788
+ x: parseInt(elPosition.left, BASE) + parseInt(pagePosition.x, BASE),
789
+ y: parseInt(elPosition.top, BASE) + parseInt(pagePosition.y, BASE),
790
+ }
791
+ }
792
+
793
+ function findTarget(location) {
794
+ function jumpToTarget(target) {
795
+ const jumpPosition = getElementPosition(target);
796
+
797
+ log(
798
+ `Moving to in page link (#${hash}) at x: ${jumpPosition.x}y: ${jumpPosition.y}`,
799
+ );
800
+
801
+ sendMsg(jumpPosition.y, jumpPosition.x, 'scrollToOffset'); // X&Y reversed at sendMsg uses height/width
802
+ }
803
+
804
+ const hash = location.split('#')[1] || location; // Remove # if present
805
+ const hashData = decodeURIComponent(hash);
806
+ const target =
807
+ document.getElementById(hashData) ||
808
+ document.getElementsByName(hashData)[0];
809
+
810
+ if (target !== undefined) {
811
+ jumpToTarget(target);
812
+ return
813
+ }
814
+
815
+ log(`In page link (#${hash}) not found in iFrame, so sending to parent`);
816
+ sendMsg(0, 0, 'inPageLink', `#${hash}`);
817
+ }
818
+
819
+ function checkLocationHash() {
820
+ const { hash, href } = window.location;
821
+
822
+ if (hash !== '' && hash !== '#') {
823
+ findTarget(href);
824
+ }
825
+ }
826
+
827
+ function bindAnchors() {
828
+ function setupLink(el) {
829
+ function linkClicked(e) {
830
+ e.preventDefault();
831
+
832
+ findTarget(this.getAttribute('href'));
833
+ }
834
+
835
+ if (el.getAttribute('href') !== '#') {
836
+ addEventListener(el, 'click', linkClicked);
837
+ }
838
+ }
839
+
840
+ document.querySelectorAll('a[href^="#"]').forEach(setupLink);
841
+ }
842
+
843
+ function bindLocationHash() {
844
+ addEventListener(window, 'hashchange', checkLocationHash);
845
+ }
846
+
847
+ function initCheck() {
848
+ // Check if page loaded with location hash after init resize
849
+ setTimeout(checkLocationHash, eventCancelTimer);
850
+ }
851
+
852
+ function enableInPageLinks() {
853
+ log('Setting up location.hash handlers');
854
+ bindAnchors();
855
+ bindLocationHash();
856
+ initCheck();
857
+ }
858
+
859
+ if (inPageLinks.enable) {
860
+ if (mode === 1) {
861
+ advise(
862
+ `In page linking requires a Professional or Business license. Please see https://iframe-resizer.com/pricing for more details.`,
863
+ );
864
+ } else {
865
+ enableInPageLinks();
866
+ }
867
+ } else {
868
+ log('In page linking not enabled');
869
+ }
870
+
871
+ return {
872
+ findTarget,
873
+ }
874
+ }
875
+
876
+ function setupMouseEvents() {
877
+ if (mouseEvents !== true) return
878
+
879
+ function sendMouse(e) {
880
+ sendMsg(0, 0, e.type, `${e.screenY}:${e.screenX}`);
881
+ }
882
+
883
+ function addMouseListener(evt, name) {
884
+ log(`Add event listener: ${name}`);
885
+ addEventListener(window.document, evt, sendMouse);
886
+ }
887
+
888
+ addMouseListener('mouseenter', 'Mouse Enter');
889
+ addMouseListener('mouseleave', 'Mouse Leave');
890
+ }
891
+
892
+ function setupPublicMethods() {
893
+ if (mode === 1) return
894
+
895
+ win.parentIframe = Object.freeze({
896
+ autoResize: (resize) => {
897
+ if (resize === true && autoResize === false) {
898
+ autoResize = true;
899
+ initEventListeners();
900
+ } else if (resize === false && autoResize === true) {
901
+ autoResize = false;
902
+ stopEventListeners();
903
+ }
904
+
905
+ sendMsg(0, 0, 'autoResize', JSON.stringify(autoResize));
906
+
907
+ return autoResize
908
+ },
909
+
910
+ close() {
911
+ sendMsg(0, 0, 'close');
912
+ },
913
+
914
+ getId: () => myID,
915
+
916
+ getPageInfo(callback) {
917
+ if (typeof callback === 'function') {
918
+ onPageInfo = callback;
919
+ sendMsg(0, 0, 'pageInfo');
920
+ advise(
921
+ `<rb>Deprecated Method</>
922
+
923
+ The <b>getPageInfo()</> method has been deprecated and replaced with <b>getParentProps()</>. Use of this method will be removed in a future version of <i>iframe-resizer</>.
924
+ `,
925
+ );
926
+ return
927
+ }
928
+
929
+ onPageInfo = null;
930
+ sendMsg(0, 0, 'pageInfoStop');
931
+ },
932
+
933
+ getParentProps(callback) {
934
+ if (typeof callback !== 'function') {
935
+ throw new TypeError(
936
+ 'parentIFrame.getParentProps(callback) callback not a function',
937
+ )
938
+ }
939
+
940
+ onParentInfo = callback;
941
+ sendMsg(0, 0, 'parentInfo');
942
+
943
+ return () => {
944
+ onParentInfo = null;
945
+ sendMsg(0, 0, 'parentInfoStop');
946
+ }
947
+ },
948
+
949
+ getParentProperties(callback) {
950
+ advise(
951
+ `<rb>Renamed Method</>
952
+
953
+ The <b>getParentProperties()</> method has been renamed <b>getParentProps()</>. Use of the old name will be removed in a future version of <i>iframe-resizer</>.
954
+ `,
955
+ );
956
+ this.getParentProps(callback);
957
+ },
958
+
959
+ moveToAnchor(hash) {
960
+ inPageLinks.findTarget(hash);
961
+ },
962
+
963
+ reset() {
964
+ resetIFrame('parentIFrame.reset');
965
+ },
966
+
967
+ scrollBy(x, y) {
968
+ sendMsg(y, x, 'scrollBy'); // X&Y reversed at sendMsg uses height/width
969
+ },
970
+
971
+ scrollTo(x, y) {
972
+ sendMsg(y, x, 'scrollTo'); // X&Y reversed at sendMsg uses height/width
973
+ },
974
+
975
+ scrollToOffset(x, y) {
976
+ sendMsg(y, x, 'scrollToOffset'); // X&Y reversed at sendMsg uses height/width
977
+ },
978
+
979
+ sendMessage(msg, targetOrigin) {
980
+ sendMsg(0, 0, 'message', JSON.stringify(msg), targetOrigin);
981
+ },
982
+
983
+ setHeightCalculationMethod(heightCalculationMethod) {
984
+ heightCalcMode = heightCalculationMethod;
985
+ checkHeightMode();
986
+ },
987
+
988
+ setWidthCalculationMethod(widthCalculationMethod) {
989
+ widthCalcMode = widthCalculationMethod;
990
+ checkWidthMode();
991
+ },
992
+
993
+ setTargetOrigin(targetOrigin) {
994
+ log(`Set targetOrigin: ${targetOrigin}`);
995
+ targetOriginDefault = targetOrigin;
996
+ },
997
+
998
+ resize(customHeight, customWidth) {
999
+ const valString = `${customHeight || ''}${customWidth ? `,${customWidth}` : ''}`;
1000
+
1001
+ sendSize(
1002
+ 'size',
1003
+ `parentIFrame.size(${valString})`,
1004
+ customHeight,
1005
+ customWidth,
1006
+ );
1007
+ },
1008
+
1009
+ size(customHeight, customWidth) {
1010
+ advise(
1011
+ `<rb>Deprecated Method</>
1012
+
1013
+ The <b>size()</> method has been deprecated and replaced with <b>resize()</>. Use of this method will be removed in a future version of <i>iframe-resizer</>.
1014
+ `,
1015
+ );
1016
+ this.resize(customHeight, customWidth);
1017
+ },
1018
+ });
1019
+
1020
+ win.parentIFrame = win.parentIframe;
1021
+ }
1022
+
1023
+ let dispatchResized;
1024
+
1025
+ function resizeObserved(entries) {
1026
+ if (!Array.isArray(entries) || entries.length === 0) return
1027
+
1028
+ const el = entries[0].target;
1029
+
1030
+ dispatchResized = () =>
1031
+ sendSize('resizeObserver', `Resize Observed: ${getElementName(el)}`);
1032
+
1033
+ // Throttle event to once per current call stack (Safari issue)
1034
+ setTimeout(() => {
1035
+ if (dispatchResized) dispatchResized();
1036
+ dispatchResized = undefined;
1037
+ }, 0);
1038
+ }
1039
+
1040
+ const checkPositionType = (element) => {
1041
+ const style = getComputedStyle(element);
1042
+ return style?.position !== '' && style?.position !== 'static'
1043
+ };
1044
+
1045
+ const getAllNonStaticElements = () =>
1046
+ [...getAllElements(document)()].filter(checkPositionType);
1047
+
1048
+ const resizeSet = new WeakSet();
1049
+
1050
+ function setupResizeObservers(el) {
1051
+ if (!el) return
1052
+ if (resizeSet.has(el)) return
1053
+ resizeObserver.observe(el);
1054
+ resizeSet.add(el);
1055
+ log(`Attached resizeObserver: ${getElementName(el)}`);
1056
+ }
1057
+
1058
+ function createResizeObservers(el) {
1059
+ [
1060
+ ...getAllNonStaticElements(),
1061
+ ...resizeObserveTargets.flatMap((target) => el.querySelector(target)),
1062
+ ].forEach(setupResizeObservers);
1063
+ }
1064
+
1065
+ function setupResizeObserver() {
1066
+ resizeObserver = new ResizeObserver(resizeObserved);
1067
+ createResizeObservers(window.document);
1068
+ }
1069
+
1070
+ function setupBodyMutationObserver() {
1071
+ const observedMutations = new Set();
1072
+ let pending = false;
1073
+ let perfMon = 0;
1074
+ let newMutations = [];
1075
+
1076
+ const updateMutation = (mutations) => {
1077
+ const { length } = mutations;
1078
+
1079
+ for (let i = 0; i < length; i++) {
1080
+ const { addedNodes, removedNodes } = mutations[i];
1081
+
1082
+ const aLen = addedNodes.length;
1083
+ const rLen = removedNodes.length;
1084
+
1085
+ if (aLen > 2) {
1086
+ log('MutationObserver: addedNodes', addedNodes);
1087
+ }
1088
+
1089
+ if (aLen) {
1090
+ for (let j = 0; j < aLen; j++) {
1091
+ observedMutations.add(addedNodes[j]);
1092
+ }
1093
+ }
1094
+
1095
+ if (rLen) {
1096
+ for (let j = 0; j < rLen; j++) {
1097
+ observedMutations.delete(removedNodes[j]);
1098
+ }
1099
+ }
1100
+ }
1101
+ };
1102
+
1103
+ const DELAY = 18;
1104
+ let delayCount = 0;
1105
+
1106
+ function processMutations() {
1107
+ const now = performance.now();
1108
+ const delay = now - perfMon;
1109
+
1110
+ // Back off if the callStack is busy with other stuff
1111
+ if (delay > DELAY * ++delayCount) {
1112
+ info(`MutationObserver delay: ${delay}ms`);
1113
+ setTimeout(processMutations, DELAY * delayCount);
1114
+ perfMon = now;
1115
+ return
1116
+ }
1117
+
1118
+ delayCount = 0;
1119
+
1120
+ newMutations.forEach(updateMutation);
1121
+ newMutations = [];
1122
+
1123
+ if (observedMutations.size === 0) {
1124
+ pending = false;
1125
+ return
1126
+ }
1127
+
1128
+ // apply sizeSelector to new elements
1129
+ applySizeSelector();
1130
+
1131
+ // Rebuild tagged elements list for size calculation
1132
+ checkAndSetupTags();
1133
+
1134
+ // Add observers to new elements
1135
+ addOverflowObservers(observedMutations);
1136
+ observedMutations.forEach(createResizeObservers);
1137
+
1138
+ observedMutations.clear();
1139
+
1140
+ pending = false;
1141
+ }
1142
+
1143
+ function mutationObserved(mutations) {
1144
+ newMutations.push(mutations);
1145
+ if (pending) return
1146
+
1147
+ perfMon = performance.now();
1148
+ pending = true;
1149
+ requestAnimationFrame(processMutations);
1150
+ }
1151
+
1152
+ function createMutationObserver() {
1153
+ const observer = new window.MutationObserver(mutationObserved);
1154
+ const target = document.querySelector('body');
1155
+ const config = {
1156
+ attributes: false,
1157
+ attributeOldValue: false,
1158
+ characterData: false,
1159
+ characterDataOldValue: false,
1160
+ childList: true,
1161
+ subtree: true,
1162
+ };
1163
+
1164
+ log('Create <body/> MutationObserver');
1165
+ observer.observe(target, config);
1166
+
1167
+ return observer
1168
+ }
1169
+
1170
+ const observer = createMutationObserver();
1171
+
1172
+ return {
1173
+ disconnect() {
1174
+ log('Disconnect MutationObserver');
1175
+ observer.disconnect();
1176
+ },
1177
+ }
1178
+ }
1179
+
1180
+ function setupMutationObserver() {
1181
+ bodyObserver = setupBodyMutationObserver();
1182
+ }
1183
+
1184
+ function getMaxElement(side) {
1185
+ performance.mark(PREF_START);
1186
+
1187
+ const Side = capitalizeFirstLetter(side);
1188
+
1189
+ let elVal = 0;
1190
+ let maxEl = document.documentElement;
1191
+ let maxVal = hasTags
1192
+ ? 0
1193
+ : document.documentElement.getBoundingClientRect().bottom;
1194
+
1195
+ performance.mark(PREF_START);
1196
+
1197
+ const targetElements = hasTags
1198
+ ? taggedElements
1199
+ : isOverflowed()
1200
+ ? getOverflowedElements()
1201
+ : getAllElements(document)(); // We should never get here, but just in case
1202
+
1203
+ let len = targetElements.length;
1204
+
1205
+ targetElements.forEach((element) => {
1206
+ if (
1207
+ !hasTags &&
1208
+ hasCheckVisibility && // Safari missing checkVisibility
1209
+ !element.checkVisibility(checkVisibilityOptions)
1210
+ ) {
1211
+ len -= 1;
1212
+ return
1213
+ }
1214
+
1215
+ elVal =
1216
+ element.getBoundingClientRect()[side] +
1217
+ parseFloat(getComputedStyle(element).getPropertyValue(`margin-${side}`));
1218
+
1219
+ if (elVal > maxVal) {
1220
+ maxVal = elVal;
1221
+ maxEl = element;
1222
+ }
1223
+ });
1224
+
1225
+ setPerfEl(maxEl);
1226
+ performance.mark(PREF_END, {
1227
+ detail: {
1228
+ Side,
1229
+ len,
1230
+ hasTags,
1231
+ logging,
1232
+ },
1233
+ });
1234
+
1235
+ return maxVal
1236
+ }
1237
+
1238
+ const getAllMeasurements = (dimension) => [
1239
+ dimension.bodyOffset(),
1240
+ dimension.bodyScroll(),
1241
+ dimension.documentElementOffset(),
1242
+ dimension.documentElementScroll(),
1243
+ dimension.documentElementBoundingClientRect(),
1244
+ ];
1245
+
1246
+ const getAllElements = (element) => () =>
1247
+ element.querySelectorAll(
1248
+ '* :not(head):not(meta):not(base):not(title):not(script):not(link):not(style):not(map):not(area):not(option):not(optgroup):not(template):not(track):not(wbr):not(nobr)',
1249
+ );
1250
+
1251
+ const prevScrollSize = {
1252
+ height: 0,
1253
+ width: 0,
1254
+ };
1255
+
1256
+ const prevBoundingSize = {
1257
+ height: 0,
1258
+ width: 0,
1259
+ };
1260
+
1261
+ const getAdjustedScroll = (getDimension) =>
1262
+ getDimension.documentElementScroll() + Math.max(0, getDimension.getOffset());
1263
+
1264
+ function getAutoSize(getDimension) {
1265
+ function returnBoundingClientRect() {
1266
+ prevBoundingSize[dimension] = boundingSize;
1267
+ prevScrollSize[dimension] = scrollSize;
1268
+ return boundingSize
1269
+ }
1270
+
1271
+ const hasOverflow = isOverflowed();
1272
+ const isHeight = getDimension === getHeight;
1273
+ const dimension = isHeight ? 'height' : 'width';
1274
+ const boundingSize = getDimension.documentElementBoundingClientRect();
1275
+ const ceilBoundingSize = Math.ceil(boundingSize);
1276
+ const floorBoundingSize = Math.floor(boundingSize);
1277
+ const scrollSize = getAdjustedScroll(getDimension);
1278
+ const sizes = `HTML: ${boundingSize} Page: ${scrollSize}`;
1279
+
1280
+ switch (true) {
1281
+ case !getDimension.enabled():
1282
+ return scrollSize
1283
+
1284
+ case hasTags:
1285
+ return getDimension.taggedElement()
1286
+
1287
+ case !hasOverflow &&
1288
+ prevBoundingSize[dimension] === 0 &&
1289
+ prevScrollSize[dimension] === 0:
1290
+ log(`Initial page size values: ${sizes}`);
1291
+ return returnBoundingClientRect()
1292
+
1293
+ case triggerLocked &&
1294
+ boundingSize === prevBoundingSize[dimension] &&
1295
+ scrollSize === prevScrollSize[dimension]:
1296
+ log(`Size unchanged: ${sizes}`);
1297
+ return Math.max(boundingSize, scrollSize)
1298
+
1299
+ case boundingSize === 0:
1300
+ log(`Page is hidden: ${sizes}`);
1301
+ return scrollSize
1302
+
1303
+ case !hasOverflow &&
1304
+ boundingSize !== prevBoundingSize[dimension] &&
1305
+ scrollSize <= prevScrollSize[dimension]:
1306
+ log(
1307
+ `New HTML bounding size: ${sizes}`,
1308
+ 'Previous bounding size:',
1309
+ prevBoundingSize[dimension],
1310
+ );
1311
+ return returnBoundingClientRect()
1312
+
1313
+ case !isHeight:
1314
+ return getDimension.taggedElement()
1315
+
1316
+ case !hasOverflow && boundingSize < prevBoundingSize[dimension]:
1317
+ log('HTML bounding size decreased:', sizes);
1318
+ return returnBoundingClientRect()
1319
+
1320
+ case scrollSize === floorBoundingSize || scrollSize === ceilBoundingSize:
1321
+ log('HTML bounding size equals page size:', sizes);
1322
+ return returnBoundingClientRect()
1323
+
1324
+ case boundingSize > scrollSize:
1325
+ log(`Page size < HTML bounding size: ${sizes}`);
1326
+ return returnBoundingClientRect()
1327
+
1328
+ default:
1329
+ log(`Content overflowing HTML element: ${sizes}`);
1330
+ }
1331
+
1332
+ return Math.max(getDimension.taggedElement(), returnBoundingClientRect())
1333
+ }
1334
+
1335
+ const getBodyOffset = () => {
1336
+ const { body } = document;
1337
+ const style = getComputedStyle(body);
1338
+
1339
+ return (
1340
+ body.offsetHeight +
1341
+ parseInt(style.marginTop, BASE) +
1342
+ parseInt(style.marginBottom, BASE)
1343
+ )
1344
+ };
1345
+
1346
+ const getHeight = {
1347
+ enabled: () => calculateHeight,
1348
+ getOffset: () => offsetHeight,
1349
+ auto: () => getAutoSize(getHeight),
1350
+ bodyOffset: getBodyOffset,
1351
+ bodyScroll: () => document.body.scrollHeight,
1352
+ offset: () => getHeight.bodyOffset(), // Backwards compatibility
1353
+ custom: () => customCalcMethods.height(),
1354
+ documentElementOffset: () => document.documentElement.offsetHeight,
1355
+ documentElementScroll: () => document.documentElement.scrollHeight,
1356
+ documentElementBoundingClientRect: () =>
1357
+ document.documentElement.getBoundingClientRect().bottom,
1358
+ max: () => Math.max(...getAllMeasurements(getHeight)),
1359
+ min: () => Math.min(...getAllMeasurements(getHeight)),
1360
+ grow: () => getHeight.max(),
1361
+ lowestElement: () => getMaxElement(HEIGHT_EDGE),
1362
+ taggedElement: () => getMaxElement(HEIGHT_EDGE),
1363
+ };
1364
+
1365
+ const getWidth = {
1366
+ enabled: () => calculateWidth,
1367
+ getOffset: () => offsetWidth,
1368
+ auto: () => getAutoSize(getWidth),
1369
+ bodyScroll: () => document.body.scrollWidth,
1370
+ bodyOffset: () => document.body.offsetWidth,
1371
+ custom: () => customCalcMethods.width(),
1372
+ documentElementScroll: () => document.documentElement.scrollWidth,
1373
+ documentElementOffset: () => document.documentElement.offsetWidth,
1374
+ documentElementBoundingClientRect: () =>
1375
+ document.documentElement.getBoundingClientRect().right,
1376
+ max: () => Math.max(...getAllMeasurements(getWidth)),
1377
+ min: () => Math.min(...getAllMeasurements(getWidth)),
1378
+ rightMostElement: () => getMaxElement(WIDTH_EDGE),
1379
+ scroll: () =>
1380
+ Math.max(getWidth.bodyScroll(), getWidth.documentElementScroll()),
1381
+ taggedElement: () => getMaxElement(WIDTH_EDGE),
1382
+ };
1383
+
1384
+ function sizeIFrame(
1385
+ triggerEvent,
1386
+ triggerEventDesc,
1387
+ customHeight,
1388
+ customWidth,
1389
+ msg,
1390
+ ) {
1391
+ function resizeIFrame() {
1392
+ height = currentHeight;
1393
+ width = currentWidth;
1394
+ sendMsg(height, width, triggerEvent, msg);
1395
+ }
1396
+
1397
+ function isSizeChangeDetected() {
1398
+ const checkTolerance = (a, b) => !(Math.abs(a - b) <= tolerance);
1399
+
1400
+ // currentHeight = Math.ceil(
1401
+ // undefined === customHeight ? getHeight[heightCalcMode]() : customHeight,
1402
+ // )
1403
+
1404
+ // currentWidth = Math.ceil(
1405
+ // undefined === customWidth ? getWidth[widthCalcMode]() : customWidth,
1406
+ // )
1407
+
1408
+ currentHeight =
1409
+ undefined === customHeight ? getHeight[heightCalcMode]() : customHeight;
1410
+ currentWidth =
1411
+ undefined === customWidth ? getWidth[widthCalcMode]() : customWidth;
1412
+
1413
+ return (
1414
+ (calculateHeight && checkTolerance(height, currentHeight)) ||
1415
+ (calculateWidth && checkTolerance(width, currentWidth))
1416
+ )
1417
+ }
1418
+
1419
+ const isForceResizableEvent = () => !(triggerEvent in { init: 1, size: 1 });
1420
+
1421
+ const isForceResizableCalcMode = () =>
1422
+ (calculateHeight && heightCalcMode in resetRequiredMethods) ||
1423
+ (calculateWidth && widthCalcMode in resetRequiredMethods);
1424
+
1425
+ function checkDownSizing() {
1426
+ if (isForceResizableEvent() && isForceResizableCalcMode()) {
1427
+ resetIFrame(triggerEventDesc);
1428
+ }
1429
+ }
1430
+
1431
+ let currentHeight;
1432
+ let currentWidth;
1433
+
1434
+ if (isSizeChangeDetected() || triggerEvent === 'init') {
1435
+ lockTrigger();
1436
+ resizeIFrame();
1437
+ } else {
1438
+ checkDownSizing();
1439
+ }
1440
+ }
1441
+
1442
+ function sendSize(
1443
+ triggerEvent,
1444
+ triggerEventDesc,
1445
+ customHeight,
1446
+ customWidth,
1447
+ msg,
1448
+ ) {
1449
+ if (document.hidden) {
1450
+ // Currently only correctly supported in firefox
1451
+ // This is checked again on the parent page
1452
+ log('Page hidden - Ignored resize request');
1453
+ return
1454
+ }
1455
+
1456
+ if (!(triggerEvent in nonLoggableTriggerEvents)) {
1457
+ log(`Trigger event: ${triggerEventDesc}`);
1458
+ }
1459
+
1460
+ sizeIFrame(triggerEvent, triggerEventDesc, customHeight, customWidth, msg);
1461
+ }
1462
+
1463
+ function lockTrigger() {
1464
+ if (triggerLocked) return
1465
+
1466
+ triggerLocked = true;
1467
+ log('Trigger event lock on');
1468
+
1469
+ requestAnimationFrame(() => {
1470
+ triggerLocked = false;
1471
+ log('Trigger event lock off');
1472
+ log('--');
1473
+ });
1474
+ }
1475
+
1476
+ function triggerReset(triggerEvent) {
1477
+ height = getHeight[heightCalcMode]();
1478
+ width = getWidth[widthCalcMode]();
1479
+
1480
+ sendMsg(height, width, triggerEvent);
1481
+ }
1482
+
1483
+ function resetIFrame(triggerEventDesc) {
1484
+ const hcm = heightCalcMode;
1485
+ heightCalcMode = heightCalcModeDefault;
1486
+
1487
+ log(`Reset trigger event: ${triggerEventDesc}`);
1488
+ lockTrigger();
1489
+ triggerReset('reset');
1490
+
1491
+ heightCalcMode = hcm;
1492
+ }
1493
+
1494
+ function sendMsg(height, width, triggerEvent, msg, targetOrigin) {
1495
+ if (mode < -1) return
1496
+
1497
+ function setTargetOrigin() {
1498
+ if (undefined === targetOrigin) {
1499
+ targetOrigin = targetOriginDefault;
1500
+ return
1501
+ }
1502
+
1503
+ log(`Message targetOrigin: ${targetOrigin}`);
1504
+ }
1505
+
1506
+ function sendToParent() {
1507
+ const size = `${height + (offsetHeight || 0)}:${width + (offsetWidth || 0)}`;
1508
+ const message = `${myID}:${size}:${triggerEvent}${undefined === msg ? '' : `:${msg}`}`;
1509
+
1510
+ log(
1511
+ `Sending message to host page (${message}) via ${sameDomain ? 'sameDomain' : 'postMessage'}`,
1512
+ );
1513
+
1514
+ if (sameDomain) {
1515
+ window.parent.iframeParentListener(msgID + message);
1516
+ return
1517
+ }
1518
+
1519
+ target.postMessage(msgID + message, targetOrigin);
1520
+ }
1521
+
1522
+ setTargetOrigin();
1523
+ sendToParent();
1524
+ }
1525
+
1526
+ function receiver(event) {
1527
+ const processRequestFromParent = {
1528
+ init: function initFromParent() {
1529
+ initMsg = event.data;
1530
+ target = event.source;
1531
+
1532
+ init();
1533
+ firstRun = false;
1534
+ setTimeout(() => {
1535
+ initLock = false;
1536
+ }, eventCancelTimer);
1537
+ },
1538
+
1539
+ reset() {
1540
+ if (initLock) {
1541
+ log('Page reset ignored by init');
1542
+ return
1543
+ }
1544
+ log('Page size reset by host page');
1545
+ triggerReset('resetPage');
1546
+ },
1547
+
1548
+ resize() {
1549
+ sendSize('resizeParent', 'Parent window requested size check');
1550
+ },
1551
+
1552
+ moveToAnchor() {
1553
+ inPageLinks.findTarget(getData());
1554
+ },
1555
+
1556
+ inPageLink() {
1557
+ this.moveToAnchor();
1558
+ }, // Backward compatibility
1559
+
1560
+ pageInfo() {
1561
+ const msgBody = getData();
1562
+ log(`PageInfo received from parent: ${msgBody}`);
1563
+ if (onPageInfo) {
1564
+ onPageInfo(JSON.parse(msgBody));
1565
+ } else {
1566
+ // not expected, so cancel more messages
1567
+ sendMsg(0, 0, 'pageInfoStop');
1568
+ }
1569
+ log(' --');
1570
+ },
1571
+
1572
+ parentInfo() {
1573
+ const msgBody = getData();
1574
+ log(`ParentInfo received from parent: ${msgBody}`);
1575
+ if (onParentInfo) {
1576
+ onParentInfo(Object.freeze(JSON.parse(msgBody)));
1577
+ } else {
1578
+ // not expected, so cancel more messages
1579
+ sendMsg(0, 0, 'parentInfoStop');
1580
+ }
1581
+ log(' --');
1582
+ },
1583
+
1584
+ message() {
1585
+ const msgBody = getData();
1586
+ log(`onMessage called from parent: ${msgBody}`);
1587
+ // eslint-disable-next-line sonarjs/no-extra-arguments
1588
+ onMessage(JSON.parse(msgBody));
1589
+ log(' --');
1590
+ },
1591
+ };
1592
+
1593
+ const isMessageForUs = () => msgID === `${event.data}`.slice(0, msgIdLen);
1594
+
1595
+ const getMessageType = () => event.data.split(']')[1].split(':')[0];
1596
+
1597
+ const getData = () => event.data.slice(event.data.indexOf(':') + 1);
1598
+
1599
+ const isMiddleTier = () =>
1600
+ 'iframeResize' in window ||
1601
+ (window.jQuery !== undefined && '' in window.jQuery.prototype);
1602
+
1603
+ // Test if this message is from a child below us. This is an ugly test, however, updating
1604
+ // the message format would break backwards compatibility.
1605
+ const isInitMsg = () => event.data.split(':')[2] in { true: 1, false: 1 };
1606
+
1607
+ function callFromParent() {
1608
+ const messageType = getMessageType();
1609
+
1610
+ if (messageType in processRequestFromParent) {
1611
+ processRequestFromParent[messageType]();
1612
+ return
1613
+ }
1614
+
1615
+ if (!isMiddleTier() && !isInitMsg()) {
1616
+ warn(`Unexpected message (${event.data})`);
1617
+ }
1618
+ }
1619
+
1620
+ function processMessage() {
1621
+ if (firstRun === false) {
1622
+ callFromParent();
1623
+ return
1624
+ }
1625
+
1626
+ if (isInitMsg()) {
1627
+ processRequestFromParent.init();
1628
+ return
1629
+ }
1630
+
1631
+ log(
1632
+ `Ignored message of type "${getMessageType()}". Received before initialization.`,
1633
+ );
1634
+ }
1635
+
1636
+ if (isMessageForUs()) {
1637
+ processMessage();
1638
+ }
1639
+ }
1640
+
1641
+ // Normally the parent kicks things off when it detects the iFrame has loaded.
1642
+ // If this script is async-loaded, then tell parent page to retry init.
1643
+ function chkLateLoaded() {
1644
+ if (document.readyState !== 'loading') {
1645
+ window.parent.postMessage('[iFrameResizerChild]Ready', '*');
1646
+ }
1647
+ }
1648
+
1649
+ window.iframeChildListener = (data) => receiver({ data, sameDomain: true });
1650
+ addEventListener(window, 'message', receiver);
1651
+ addEventListener(window, 'readystatechange', chkLateLoaded);
1652
+ chkLateLoaded();
1653
+
1654
+ }
1655
+
1656
+ // Don't run for server side render
1657
+ if (typeof window !== 'undefined') {
1658
+ iframeResizerChild();
1659
+ }