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