@iframe-resizer/child 5.0.0 → 5.0.2

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.esm.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /*!
2
2
  * @preserve
3
3
  *
4
- * @module iframe-resizer/child 5.0.0 (esm) - 2024-05-19
4
+ * @module iframe-resizer/child 5.0.2 (esm) - 2024-05-30
5
5
  *
6
6
  * @license GPL-3.0 for non-commercial use only.
7
7
  * For commercial use, you must purchase a license from
@@ -9,7 +9,7 @@
9
9
  *
10
10
  * @desciption Keep same and cross domain iFrames sized to their content
11
11
  *
12
- * @author David J. Bradshaw <dave@bradshaw.net>
12
+ * @author David J. Bradshaw <info@iframe-resizer.com>
13
13
  *
14
14
  * @see {@link https://iframe-resizer.com}
15
15
  *
@@ -17,4 +17,1288 @@
17
17
  */
18
18
 
19
19
 
20
- const e="5.0.0",t=10,n="data-iframe-size",o=(e,t,n,o)=>e.addEventListener(t,n,o||!1),i=(e,t,n)=>e.removeEventListener(t,n,!1),r=["<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 a=e=>(e=>e.replaceAll(/[A-Za-z]/g,(e=>String.fromCodePoint((e<="Z"?90:122)>=(e=e.codePointAt(0)+19)?e:e-26))))(r[e]),l={contentVisibilityAuto:!0,opacityProperty:!0,visibilityProperty:!0},c={height:()=>(re("Custom height calculation function not defined"),Te.auto()),width:()=>(re("Custom width calculation function not defined"),Ie.auto())},s={bodyOffset:1,bodyScroll:1,offset:1,documentElementOffset:1,documentElementScroll:1,documentElementBoundingClientRect:1,max:1,min:1,grow:1,lowestElement:1},u=128,d={},m="checkVisibility"in window,f="auto",p="[iFrameSizer]",h=p.length,y={max:1,min:1,bodyScroll:1,documentElementScroll:1},g=["body"],v="scroll";let b,w,z=!0,S="",$=0,j="",E=null,O="",M=!0,C=!1,P=null,A=!0,T=!1,I=1,k=f,x=!0,N="",R={},B=!0,L=!1,q=0,D=!1,H="",W="child",F=null,U=!1,V=window.parent,J="*",Z=0,Q=!1,X="",Y=1,G=v,K=window,_=()=>{re("onMessage function not defined")},ee=()=>{},te=null,ne=null;const oe=e=>""!=`${e}`&&void 0!==e;const ie=(...e)=>[`[iframe-resizer][${H}]`,...e].join(" "),re=(...e)=>console?.warn(ie(...e)),ae=(...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,"")))(ie)(...e)),le=e=>ae(e);function ce(){!function(){try{U="iframeParentListener"in window.parent}catch(e){}}(),function(){const e=e=>"true"===e,t=N.slice(h).split(":");H=t[0],$=void 0===t[1]?$:Number(t[1]),C=void 0===t[2]?C:e(t[2]),L=void 0===t[3]?L:e(t[3]),z=void 0===t[6]?z:e(t[6]),j=t[7],k=void 0===t[8]?k:t[8],S=t[9],O=t[10],Z=void 0===t[11]?Z:Number(t[11]),R.enable=void 0!==t[12]&&e(t[12]),W=void 0===t[13]?W:t[13],G=void 0===t[14]?G:t[14],D=void 0===t[15]?D:e(t[15]),b=void 0===t[16]?b:Number(t[16]),w=void 0===t[17]?w:Number(t[17]),M=void 0===t[18]?M:e(t[18]),t[19],X=t[20]||X,q=void 0===t[21]?q:Number(t[21])}(),function(){function e(){const e=window.iframeResizer||window.iFrameResizer;_=e?.onMessage||_,ee=e?.onReady||ee,"number"==typeof e?.offset&&(M&&(b=e?.offset),C&&(w=e?.offset)),J=e?.targetOrigin||J,k=e?.heightCalculationMethod||k,G=e?.widthCalculationMethod||G}function t(e,t){return"function"==typeof e&&(c[t]=e,e="custom"),e}if(1===q)return;"iFrameResizer"in window&&Object===window.iFrameResizer.constructor&&(e(),k=t(k,"height"),G=t(G,"width"))}(),function(){void 0===j&&(j=`${$}px`);se("margin",function(e,t){t.includes("-")&&(re(`Negative CSS value ignored for ${e}`),t="");return t}("margin",j))}(),se("background",S),se("padding",O),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)}(),q<0?le(`${a(q+2)}${a(2)}`):X.codePointAt(0)>4||q<2&&le(a(3)),function(){if(!X||""===X||"false"===X)return void ae("<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/<u> for more details.\n");X!==e&&ae(`<rb>Version mismatch</>\n\nThe parent and child pages are running different versions of <i>iframe resizer</>.\n\nParent page: ${X} - Child page: ${e}.\n`)}(),pe(),he(),function(){let e=!1;const t=t=>document.querySelectorAll(`[${t}]`).forEach((o=>{e=!0,o.removeAttribute(t),o.setAttribute(n,null)}));t("data-iframe-height"),t("data-iframe-width"),e&&ae("<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</>.")}(),document.querySelectorAll(`[${n}]`).length>0&&("auto"===k&&(k="autoOverflow"),"auto"===G&&(G="autoOverflow")),me(),function(){if(1===q)return;K.parentIframe=Object.freeze({autoResize:e=>(!0===e&&!1===z?(z=!0,ye()):!1===e&&!0===z&&(z=!1,de("remove"),F?.disconnect(),E?.disconnect()),Le(0,0,"autoResize",JSON.stringify(z)),z),close(){Le(0,0,"close")},getId:()=>H,getPageInfo(e){if("function"==typeof e)return te=e,Le(0,0,"pageInfo"),void ae("<rb>Deprecated Method</>\n \nThe <b>getPageInfo()</> method has been deprecated and replaced with <b>getParentProperties()</>. Use of this method will be removed in a future version of <i>iframe-resizer</>.\n");te=null,Le(0,0,"pageInfoStop")},getParentProperties(e){if("function"!=typeof e)throw new TypeError("parentIFrame.getParentProperties(callback) callback not a function");return ne=e,Le(0,0,"parentInfo"),()=>{ne=null,Le(0,0,"parentInfoStop")}},moveToAnchor(e){R.findTarget(e)},reset(){Be()},scrollTo(e,t){Le(t,e,"scrollTo")},scrollToOffset(e,t){Le(t,e,"scrollToOffset")},sendMessage(e,t){Le(0,0,"message",JSON.stringify(e),t)},setHeightCalculationMethod(e){k=e,pe()},setWidthCalculationMethod(e){G=e,he()},setTargetOrigin(e){J=e},resize(e,t){xe("size",`parentIFrame.size(${`${e||""}${t?`,${t}`:""}`})`,e,t)},size(e,t){ae("<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)}}),K.parentIFrame=K.parentIframe}(),function(){if(!0!==D)return;function e(e){Le(0,0,e.type,`${e.screenY}:${e.screenX}`)}function t(t,n){o(window.document,t,e)}t("mouseenter"),t("mouseleave")}(),ye(),R=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 i(e){function t(e){const t=n(e);Le(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?Le(0,0,"inPageLink",`#${o}`):t(r)}function r(){const{hash:e,href:t}=window.location;""!==e&&"#"!==e&&i(t)}function a(){function e(e){function t(e){e.preventDefault(),i(this.getAttribute("href"))}"#"!==e.getAttribute("href")&&o(e,"click",t)}document.querySelectorAll('a[href^="#"]').forEach(e)}function l(){o(window,"hashchange",r)}function c(){setTimeout(r,u)}function s(){a(),l(),c()}R.enable&&(1===q?ae("In page linking requires a Professional or Business license. Please see https://iframe-resizer.com/pricing for more details."):s());return{findTarget:i}}(),xe("init","Init message from host page",void 0,void 0,e),ee(),B=!1}function se(e,t){void 0!==t&&""!==t&&"null"!==t&&document.body.style.setProperty(e,t)}function ue(e){({add(t){function n(){xe(e.eventName,e.eventType)}d[t]=n,o(window,t,n,{passive:!0})},remove(e){const t=d[e];delete d[e],i(window,e,t)}})[e.method](e.eventName)}function de(e){ue({method:e,eventType:"After Print",eventName:"afterprint"}),ue({method:e,eventType:"Before Print",eventName:"beforeprint"}),ue({method:e,eventType:"Ready State Change",eventName:"readystatechange"})}function me(){const e=document.querySelectorAll(`[${n}]`);T=e.length>0,P=T?e:Ee(document)()}function fe(e,t,n,o){return t!==e&&(e in n||(re(`${e} is not a valid option for ${o}CalculationMethod.`),e=t),e in s&&ae(`<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.`)),e}function pe(){k=fe(k,f,Te,"height")}function he(){G=fe(G,v,Ie,"width")}function ye(){!0===z&&(de("add"),E=function(){function e(e){e.forEach(Se),me()}function t(){const t=new window.MutationObserver(e),n=document.querySelector("body"),o={attributes:!1,attributeOldValue:!1,characterData:!1,characterDataOldValue:!1,childList:!0,subtree:!0};return t.observe(n,o),t}const n=t();return{disconnect(){n.disconnect()}}}(),F=new ResizeObserver(ge),ze(window.document))}function ge(e){xe("resizeObserver",`resizeObserver: ${function(e){switch(!0){case!oe(e):return"";case oe(e.id):return`${e.nodeName.toUpperCase()}#${e.id}`;case oe(e.name):return`${e.nodeName.toUpperCase()} (${e.name})`;default:return e.nodeName.toUpperCase()+(oe(e.className)?`.${e.className}`:"")}}(e[0].target)}`)}const ve=e=>{const t=getComputedStyle(e);return""!==t?.position&&"static"!==t?.position},be=()=>[...Ee(document)()].filter(ve);function we(e){e&&F.observe(e)}function ze(e){[...be(),...g.flatMap((t=>e.querySelector(t)))].forEach(we)}function Se(e){"childList"===e.type&&ze(e.target)}function $e(e){const t=(n=e).charAt(0).toUpperCase()+n.slice(1);var n;let o,i=0,r=P.length,a=0,c=performance.now();P.forEach((t=>{T||!m||t.checkVisibility(l)?(i=t.getBoundingClientRect()[e]+parseFloat(getComputedStyle(t).getPropertyValue(`margin-${e}`)),i>a&&(a=i,o=t)):r-=1})),c=performance.now()-c;const s=`\nParsed ${r} element${r=""} in ${c.toPrecision(3)}ms\n${t} ${T?"tagged ":""}element found at: ${a}px\nPosition calculated from HTML element: ${function(e){const t=e?.outerHTML?.toString();return t?t.length<30?t:`${t.slice(0,30).replaceAll("\n"," ")}...`:e}(o)}`;return c<1.1||B||T||ae(`<rb>Performance Warning</>\n\nCalculating the page size took an excessive amount of time. To improve performace add the <b>data-iframe-size</> attribute to the ${e} most element on the page.\n${s}`),a}const je=e=>[e.bodyOffset(),e.bodyScroll(),e.documentElementOffset(),e.documentElementScroll(),e.documentElementBoundingClientRect()],Ee=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)");let Oe=!1;function Me({ceilBoundingSize:e,dimension:t,getDimension:n,isHeight:o,scrollSize:i}){if(!Oe)return Oe=!0,n.taggedElement();const r=o?"bottom":"right";return ae(`<rb>Detected content overflowing html element</>\n \nThis causes <i>iframe-resizer</> to fall back to checking the position of every element on the page in order to calculate the correct dimensions of the iframe. Inspecting the size, ${r} margin, and position of every visible HTML element will have a performance impact on more complex pages. \n\nTo fix this issue, and remove this warning, you can either ensure the content of the page does not overflow the <b><HTML></> element or alternatively you can add the attribute <b>data-iframe-size</> to the elements on the page that you want <i>iframe-resizer</> to use when calculating the dimensions of the iframe. \n \nWhen present the <i>${r} margin of the ${o?"lowest":"right most"} element</> with a <b>data-iframe-size</> attribute will be used to set the ${t} of the iframe.\n \n(Page size: ${i} > document size: ${e})`),o?k="autoOverflow":G="autoOverflow",n.taggedElement()}const Ce={height:0,width:0},Pe={height:0,width:0};function Ae(e,t){function n(){return Pe[i]=r,Ce[i]=c,r}const o=e===Te,i=o?"height":"width",r=e.documentElementBoundingClientRect(),a=Math.ceil(r),l=Math.floor(r),c=(e=>e.documentElementScroll()+Math.max(0,e.getOffset()))(e);switch(!0){case!e.enabled():return c;case!t&&0===Pe[i]&&0===Ce[i]:if(e.taggedElement(!0)<=a)return n();break;case Q&&r===Pe[i]&&c===Ce[i]:return Math.max(r,c);case 0===r:return c;case!t&&r!==Pe[i]&&c<=Ce[i]:return n();case!o:return t?e.taggedElement():Me({ceilBoundingSize:a,dimension:i,getDimension:e,isHeight:o,scrollSize:c});case!t&&r<Pe[i]:case c===l||c===a:case r>c:return n();case!t:return Me({ceilBoundingSize:a,dimension:i,getDimension:e,isHeight:o,scrollSize:c})}return Math.max(e.taggedElement(),n())}const Te={enabled:()=>M,getOffset:()=>b,type:"height",auto:()=>Ae(Te,!1),autoOverflow:()=>Ae(Te,!0),bodyOffset:()=>{const{body:e}=document,n=getComputedStyle(e);return e.offsetHeight+parseInt(n.marginTop,t)+parseInt(n.marginBottom,t)},bodyScroll:()=>document.body.scrollHeight,offset:()=>Te.bodyOffset(),custom:()=>c.height(),documentElementOffset:()=>document.documentElement.offsetHeight,documentElementScroll:()=>document.documentElement.scrollHeight,documentElementBoundingClientRect:()=>document.documentElement.getBoundingClientRect().bottom,max:()=>Math.max(...je(Te)),min:()=>Math.min(...je(Te)),grow:()=>Te.max(),lowestElement:()=>$e("bottom"),taggedElement:()=>$e("bottom")},Ie={enabled:()=>C,getOffset:()=>w,type:"width",auto:()=>Ae(Ie,!1),autoOverflow:()=>Ae(Ie,!0),bodyScroll:()=>document.body.scrollWidth,bodyOffset:()=>document.body.offsetWidth,custom:()=>c.width(),documentElementScroll:()=>document.documentElement.scrollWidth,documentElementOffset:()=>document.documentElement.offsetWidth,documentElementBoundingClientRect:()=>document.documentElement.getBoundingClientRect().right,max:()=>Math.max(...je(Ie)),min:()=>Math.min(...je(Ie)),rightMostElement:()=>$e("right"),scroll:()=>Math.max(Ie.bodyScroll(),Ie.documentElementScroll()),taggedElement:()=>$e("right")};function ke(e,t,n,o,i){let r,a;!function(){const e=(e,t)=>!(Math.abs(e-t)<=Z);return r=void 0===n?Te[k]():n,a=void 0===o?Ie[G]():o,M&&e(I,r)||C&&e(Y,a)}()&&"init"!==e?!(e in{init:1,size:1})&&(M&&k in y||C&&G in y)&&Be():(Ne(),I=r,Y=a,Le(I,Y,e,i))}function xe(e,t,n,o,i){document.hidden||ke(e,0,n,o,i)}function Ne(){Q||(Q=!0,requestAnimationFrame((()=>{Q=!1})))}function Re(e){I=Te[k](),Y=Ie[G](),Le(I,Y,e)}function Be(e){const t=k;k=f,Ne(),Re("reset"),k=t}function Le(e,t,n,o,i){q<0||(void 0!==i||(i=J),function(){const r=`${H}:${`${e+(b||0)}:${t+(w||0)}`}:${n}${void 0===o?"":`:${o}`}`;U?window.parent.iframeParentListener(p+r):V.postMessage(p+r,i)}())}function qe(e){const t={init:function(){N=e.data,V=e.source,ce(),A=!1,setTimeout((()=>{x=!1}),u)},reset(){x||Re("resetPage")},resize(){xe("resizeParent")},moveToAnchor(){R.findTarget(o())},inPageLink(){this.moveToAnchor()},pageInfo(){const e=o();te?te(JSON.parse(e)):Le(0,0,"pageInfoStop")},parentInfo(){const e=o();ne?ne(Object.freeze(JSON.parse(e))):Le(0,0,"parentInfoStop")},message(){const e=o();_(JSON.parse(e))}},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};p===`${e.data}`.slice(0,h)&&(!1!==A?r()&&t.init():function(){const o=n();o in t?t[o]():i()||r()||re(`Unexpected message (${e.data})`)}())}function De(){"loading"!==document.readyState&&window.parent.postMessage("[iFrameResizerChild]Ready","*")}function He(e){return qe(e),K}"undefined"!=typeof window&&(window.iframeChildListener=e=>qe({data:e,sameDomain:!0}),o(window,"message",qe),o(window,"readystatechange",De),De());try{top?.document?.getElementById("banner")&&(K={},window.mockMsgListener=He,i(window,"message",qe),define([],(()=>He)))}catch(e){}
20
+ const VERSION = '5.0.2';
21
+
22
+ const BASE = 10;
23
+ const SIZE_ATTR = 'data-iframe-size';
24
+
25
+ const encode = (s) =>
26
+ s
27
+ .replaceAll('<br>', '\n')
28
+ .replaceAll('<rb>', '\u001B[31;1m')
29
+ .replaceAll('</>', '\u001B[m')
30
+ .replaceAll('<b>', '\u001B[1m')
31
+ .replaceAll('<i>', '\u001B[3m')
32
+ .replaceAll('<u>', '\u001B[4m');
33
+
34
+ const remove = (s) => s.replaceAll('<br>', '\n').replaceAll(/<[/a-z]+>/gi, '');
35
+
36
+ const formatAdvise = (formatLogMsg) => (msg) =>
37
+ window.chrome // Only show formatting in Chrome as not supported in other browsers
38
+ ? formatLogMsg(encode(msg))
39
+ : formatLogMsg(remove(msg));
40
+
41
+ const addEventListener = (el, evt, func, options) =>
42
+ el.addEventListener(evt, func, options || false);
43
+
44
+ const removeEventListener = (el, evt, func) =>
45
+ el.removeEventListener(evt, func, false);
46
+
47
+ const p = (l) =>
48
+ l.replaceAll(/[A-Za-z]/g, (l) =>
49
+ String.fromCodePoint(
50
+ (l <= 'Z' ? 90 : 122) >= (l = l.codePointAt(0) + 19) ? l : l - 26,
51
+ ),
52
+ ),
53
+ y = [
54
+ '<iy><yi>Puchspk Spjluzl Rlf</><iy><iy>',
55
+ '<iy><yi>Tpzzpun Spjluzl Rlf</><iy><iy>',
56
+ '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</>',
57
+ '<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</>.',
58
+ ];
59
+ Object.fromEntries(
60
+ [
61
+ '2cgs7fdf4xb',
62
+ '1c9ctcccr4z',
63
+ '1q2pc4eebgb',
64
+ 'ueokt0969w',
65
+ 'w2zxchhgqz',
66
+ '1umuxblj2e5',
67
+ ].map((l, p) => [l, Math.max(0, p - 1)]),
68
+ );
69
+ const getModeData = (l) => p(y[l]);
70
+
71
+ const checkVisibilityOptions = {
72
+ contentVisibilityAuto: true,
73
+ opacityProperty: true,
74
+ visibilityProperty: true,
75
+ };
76
+ const customCalcMethods = {
77
+ height: () => {
78
+ warn('Custom height calculation function not defined');
79
+ return getHeight.auto()
80
+ },
81
+ width: () => {
82
+ warn('Custom width calculation function not defined');
83
+ return getWidth.auto()
84
+ },
85
+ };
86
+ const deprecatedResizeMethods = {
87
+ bodyOffset: 1,
88
+ bodyScroll: 1,
89
+ offset: 1,
90
+ documentElementOffset: 1,
91
+ documentElementScroll: 1,
92
+ documentElementBoundingClientRect: 1,
93
+ max: 1,
94
+ min: 1,
95
+ grow: 1,
96
+ lowestElement: 1,
97
+ };
98
+ const eventCancelTimer = 128;
99
+ const eventHandlersByName = {};
100
+ const hasCheckVisibility = 'checkVisibility' in window;
101
+ const heightCalcModeDefault = 'auto';
102
+ const msgID = '[iFrameSizer]'; // Must match host page msg ID
103
+ const msgIdLen = msgID.length;
104
+ const resetRequiredMethods = {
105
+ max: 1,
106
+ min: 1,
107
+ bodyScroll: 1,
108
+ documentElementScroll: 1,
109
+ };
110
+ const resizeObserveTargets = ['body'];
111
+ const widthCalcModeDefault = 'scroll';
112
+
113
+ let autoResize = true;
114
+ let bodyBackground = '';
115
+ let bodyMargin = 0;
116
+ let bodyMarginStr = '';
117
+ let bodyObserver = null;
118
+ let bodyPadding = '';
119
+ let calculateHeight = true;
120
+ let calculateWidth = false;
121
+ let calcElements = null;
122
+ let firstRun = true;
123
+ let hasTags = false;
124
+ let height = 1;
125
+ let heightCalcMode = heightCalcModeDefault; // only applys if not provided by host page (V1 compatibility)
126
+ let initLock = true;
127
+ let initMsg = '';
128
+ let inPageLinks = {};
129
+ let isInit = true;
130
+ let logging = false;
131
+ let mode = 0;
132
+ let mouseEvents = false;
133
+ let myID = '';
134
+ let offsetHeight;
135
+ let offsetWidth;
136
+ let resizeFrom = 'child';
137
+ let resizeObserver = null;
138
+ let sameDomain = false;
139
+ let target = window.parent;
140
+ let targetOriginDefault = '*';
141
+ let tolerance = 0;
142
+ let triggerLocked = false;
143
+ let version = '';
144
+ let width = 1;
145
+ let widthCalcMode = widthCalcModeDefault;
146
+ let win = window;
147
+
148
+ let onMessage = () => {
149
+ warn('onMessage function not defined');
150
+ };
151
+ let onReady = () => {};
152
+ let onPageInfo = null;
153
+ let onParentInfo = null;
154
+
155
+ const capitalizeFirstLetter = (string) =>
156
+ string.charAt(0).toUpperCase() + string.slice(1);
157
+
158
+ const isDef = (value) => `${value}` !== '' && value !== undefined;
159
+
160
+ function getElementName(el) {
161
+ switch (true) {
162
+ case !isDef(el):
163
+ return ''
164
+
165
+ case isDef(el.id):
166
+ return `${el.nodeName.toUpperCase()}#${el.id}`
167
+
168
+ case isDef(el.name):
169
+ return `${el.nodeName.toUpperCase()} (${el.name})`
170
+
171
+ default:
172
+ return (
173
+ el.nodeName.toUpperCase() +
174
+ (isDef(el.className) ? `.${el.className}` : '')
175
+ )
176
+ }
177
+ }
178
+
179
+ function elementSnippet(el) {
180
+ const outer = el?.outerHTML?.toString();
181
+
182
+ if (!outer) return el
183
+
184
+ return outer.length < 30
185
+ ? outer
186
+ : `${outer.slice(0, 30).replaceAll('\n', ' ')}...`
187
+ }
188
+
189
+ // TODO: remove .join(' '), requires major test updates
190
+ const formatLogMsg = (...msg) => [`[iframe-resizer][${myID}]`, ...msg].join(' ');
191
+
192
+ // const info = (...msg) =>
193
+ // // eslint-disable-next-line no-console
194
+ // console?.info(formatAdvise(...msg))
195
+
196
+ const warn = (...msg) =>
197
+ // eslint-disable-next-line no-console
198
+ console?.warn(formatLogMsg(...msg));
199
+
200
+ const advise = (...msg) =>
201
+ // eslint-disable-next-line no-console
202
+ console?.warn(formatAdvise(formatLogMsg)(...msg));
203
+
204
+ const adviser = (msg) => advise(msg);
205
+
206
+ function init() {
207
+ checkCrossDomain();
208
+ readDataFromParent();
209
+ readDataFromPage();
210
+ setMargin();
211
+ setBodyStyle('background', bodyBackground);
212
+ setBodyStyle('padding', bodyPadding);
213
+ injectClearFixIntoBodyElement();
214
+ stopInfiniteResizingOfIFrame();
215
+ checkMode();
216
+ checkVersion();
217
+ checkHeightMode();
218
+ checkWidthMode();
219
+ checkDeprecatedAttrs();
220
+ checkHasDataSizeAttributes();
221
+ setupCalcElements();
222
+ setupPublicMethods();
223
+ setupMouseEvents();
224
+ startEventListeners();
225
+ inPageLinks = setupInPageLinks();
226
+ sendSize('init', 'Init message from host page', undefined, undefined, VERSION);
227
+ onReady();
228
+ isInit = false;
229
+ }
230
+
231
+ function checkVersion() {
232
+ if (!version || version === '' || version === 'false') {
233
+ advise(
234
+ `<rb>Legacy version detected on parent page</>
235
+
236
+ Detected legacy version of parent page script. It is recommended to update the parent page to use <b>@iframe-resizer/parent</>.
237
+
238
+ See <u>https://iframe-resizer.com/setup/<u> for more details.
239
+ `,
240
+ );
241
+ return
242
+ }
243
+
244
+ if (version !== VERSION) {
245
+ advise(
246
+ `<rb>Version mismatch</>
247
+
248
+ The parent and child pages are running different versions of <i>iframe resizer</>.
249
+
250
+ Parent page: ${version} - Child page: ${VERSION}.
251
+ `,
252
+ );
253
+ }
254
+ }
255
+
256
+ function checkCrossDomain() {
257
+ try {
258
+ sameDomain = 'iframeParentListener' in window.parent;
259
+ } catch (error) {
260
+ }
261
+ }
262
+
263
+ function readDataFromParent() {
264
+ const strBool = (str) => str === 'true';
265
+ const data = initMsg.slice(msgIdLen).split(':');
266
+
267
+ myID = data[0]; // eslint-disable-line prefer-destructuring
268
+ bodyMargin = undefined === data[1] ? bodyMargin : Number(data[1]); // For V1 compatibility
269
+ calculateWidth = undefined === data[2] ? calculateWidth : strBool(data[2]);
270
+ logging = undefined === data[3] ? logging : strBool(data[3]);
271
+ // data[4] no longer used (was intervalTimer)
272
+ autoResize = undefined === data[6] ? autoResize : strBool(data[6]);
273
+ bodyMarginStr = data[7]; // eslint-disable-line prefer-destructuring
274
+ heightCalcMode = undefined === data[8] ? heightCalcMode : data[8];
275
+ bodyBackground = data[9]; // eslint-disable-line prefer-destructuring
276
+ bodyPadding = data[10]; // eslint-disable-line prefer-destructuring
277
+ tolerance = undefined === data[11] ? tolerance : Number(data[11]);
278
+ inPageLinks.enable = undefined === data[12] ? false : strBool(data[12]);
279
+ resizeFrom = undefined === data[13] ? resizeFrom : data[13];
280
+ widthCalcMode = undefined === data[14] ? widthCalcMode : data[14];
281
+ mouseEvents = undefined === data[15] ? mouseEvents : strBool(data[15]);
282
+ offsetHeight = undefined === data[16] ? offsetHeight : Number(data[16]);
283
+ offsetWidth = undefined === data[17] ? offsetWidth : Number(data[17]);
284
+ calculateHeight = undefined === data[18] ? calculateHeight : strBool(data[18]);
285
+ data[19]; // eslint-disable-line prefer-destructuring
286
+ version = data[20] || version;
287
+ mode = undefined === data[21] ? mode : Number(data[21]);
288
+ }
289
+
290
+ function readDataFromPage() {
291
+ function readData() {
292
+ const data = window.iframeResizer || window.iFrameResizer;
293
+
294
+ onMessage = data?.onMessage || onMessage;
295
+ onReady = data?.onReady || onReady;
296
+
297
+ if (typeof data?.offset === 'number') {
298
+ if (calculateHeight) offsetHeight = data?.offset;
299
+ if (calculateWidth) offsetWidth = data?.offset;
300
+ }
301
+
302
+ targetOriginDefault = data?.targetOrigin || targetOriginDefault;
303
+ heightCalcMode = data?.heightCalculationMethod || heightCalcMode;
304
+ widthCalcMode = data?.widthCalculationMethod || widthCalcMode;
305
+ }
306
+
307
+ function setupCustomCalcMethods(calcMode, calcFunc) {
308
+ if (typeof calcMode === 'function') {
309
+ customCalcMethods[calcFunc] = calcMode;
310
+ calcMode = 'custom';
311
+ }
312
+
313
+ return calcMode
314
+ }
315
+
316
+ if (mode === 1) return
317
+
318
+ if (
319
+ 'iFrameResizer' in window &&
320
+ Object === window.iFrameResizer.constructor
321
+ ) {
322
+ readData();
323
+ heightCalcMode = setupCustomCalcMethods(heightCalcMode, 'height');
324
+ widthCalcMode = setupCustomCalcMethods(widthCalcMode, 'width');
325
+ }
326
+ }
327
+
328
+ function chkCSS(attr, value) {
329
+ if (value.includes('-')) {
330
+ warn(`Negative CSS value ignored for ${attr}`);
331
+ value = '';
332
+ }
333
+
334
+ return value
335
+ }
336
+
337
+ function setBodyStyle(attr, value) {
338
+ if (undefined !== value && value !== '' && value !== 'null') {
339
+ document.body.style.setProperty(attr, value);
340
+ }
341
+ }
342
+
343
+ function setMargin() {
344
+ // If called via V1 script, convert bodyMargin from int to str
345
+ if (undefined === bodyMarginStr) {
346
+ bodyMarginStr = `${bodyMargin}px`;
347
+ }
348
+
349
+ setBodyStyle('margin', chkCSS('margin', bodyMarginStr));
350
+ }
351
+
352
+ function stopInfiniteResizingOfIFrame() {
353
+ const setAutoHeight = (el) =>
354
+ el.style.setProperty('height', 'auto', 'important');
355
+
356
+ setAutoHeight(document.documentElement);
357
+ setAutoHeight(document.body);
358
+ }
359
+
360
+ function manageTriggerEvent(options) {
361
+ const listener = {
362
+ add(eventName) {
363
+ function handleEvent() {
364
+ sendSize(options.eventName, options.eventType);
365
+ }
366
+
367
+ eventHandlersByName[eventName] = handleEvent;
368
+
369
+ addEventListener(window, eventName, handleEvent, { passive: true });
370
+ },
371
+ remove(eventName) {
372
+ const handleEvent = eventHandlersByName[eventName];
373
+ delete eventHandlersByName[eventName];
374
+
375
+ removeEventListener(window, eventName, handleEvent);
376
+ },
377
+ };
378
+
379
+ listener[options.method](options.eventName);
380
+ }
381
+
382
+ function manageEventListeners(method) {
383
+ manageTriggerEvent({
384
+ method,
385
+ eventType: 'After Print',
386
+ eventName: 'afterprint',
387
+ });
388
+
389
+ manageTriggerEvent({
390
+ method,
391
+ eventType: 'Before Print',
392
+ eventName: 'beforeprint',
393
+ });
394
+
395
+ manageTriggerEvent({
396
+ method,
397
+ eventType: 'Ready State Change',
398
+ eventName: 'readystatechange',
399
+ });
400
+
401
+ // manageTriggerEvent({
402
+ // method: method,
403
+ // eventType: 'Orientation Change',
404
+ // eventName: 'orientationchange'
405
+ // })
406
+ }
407
+
408
+ function checkDeprecatedAttrs() {
409
+ let found = false;
410
+
411
+ const checkAttrs = (attr) =>
412
+ document.querySelectorAll(`[${attr}]`).forEach((el) => {
413
+ found = true;
414
+ el.removeAttribute(attr);
415
+ el.setAttribute(SIZE_ATTR, null);
416
+ });
417
+
418
+ checkAttrs('data-iframe-height');
419
+ checkAttrs('data-iframe-width');
420
+
421
+ if (found) {
422
+ advise(
423
+ `<rb>Deprecated Attributes</>
424
+
425
+ 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</>.`,
426
+ );
427
+ }
428
+ }
429
+
430
+ function checkHasDataSizeAttributes() {
431
+ if (document.querySelectorAll(`[${SIZE_ATTR}]`).length > 0) {
432
+ if (heightCalcMode === 'auto') {
433
+ heightCalcMode = 'autoOverflow';
434
+ }
435
+ if (widthCalcMode === 'auto') {
436
+ widthCalcMode = 'autoOverflow';
437
+ }
438
+ }
439
+ }
440
+
441
+ function setupCalcElements() {
442
+ const taggedElements = document.querySelectorAll(`[${SIZE_ATTR}]`);
443
+ hasTags = taggedElements.length > 0;
444
+ calcElements = hasTags ? taggedElements : getAllElements(document)();
445
+ }
446
+
447
+ function checkCalcMode(calcMode, calcModeDefault, modes, type) {
448
+ if (calcModeDefault !== calcMode) {
449
+ if (!(calcMode in modes)) {
450
+ warn(`${calcMode} is not a valid option for ${type}CalculationMethod.`);
451
+ calcMode = calcModeDefault;
452
+ }
453
+ if (calcMode in deprecatedResizeMethods) {
454
+ advise(
455
+ `<rb>Deprecated ${type}CalculationMethod (${calcMode})</>
456
+
457
+ This version of <i>iframe-resizer</> can auto detect the most suitable ${type} calculation method. It is recommended that you remove this option.`,
458
+ );
459
+ }
460
+ }
461
+
462
+ return calcMode
463
+ }
464
+
465
+ function checkHeightMode() {
466
+ heightCalcMode = checkCalcMode(
467
+ heightCalcMode,
468
+ heightCalcModeDefault,
469
+ getHeight,
470
+ 'height',
471
+ );
472
+ }
473
+
474
+ function checkWidthMode() {
475
+ widthCalcMode = checkCalcMode(
476
+ widthCalcMode,
477
+ widthCalcModeDefault,
478
+ getWidth,
479
+ 'width',
480
+ );
481
+ }
482
+
483
+ function checkMode() {
484
+ if (mode < 0) return adviser(`${getModeData(mode + 2)}${getModeData(2)}`)
485
+ if (version.codePointAt(0) > 4) return mode
486
+ if (mode < 2) return adviser(getModeData(3))
487
+ return mode
488
+ }
489
+
490
+ function startEventListeners() {
491
+ if (autoResize !== true) {
492
+ return
493
+ }
494
+
495
+ manageEventListeners('add');
496
+ setupMutationObserver();
497
+ setupResizeObserver();
498
+ }
499
+
500
+ function stopEventListeners() {
501
+ manageEventListeners('remove');
502
+ resizeObserver?.disconnect();
503
+ bodyObserver?.disconnect();
504
+ }
505
+
506
+ function injectClearFixIntoBodyElement() {
507
+ const clearFix = document.createElement('div');
508
+
509
+ clearFix.style.clear = 'both';
510
+ // Guard against the following having been globally redefined in CSS.
511
+ clearFix.style.display = 'block';
512
+ clearFix.style.height = '0';
513
+ document.body.append(clearFix);
514
+ }
515
+
516
+ function setupInPageLinks() {
517
+ const getPagePosition = () => ({
518
+ x: document.documentElement.scrollLeft,
519
+ y: document.documentElement.scrollTop,
520
+ });
521
+
522
+ function getElementPosition(el) {
523
+ const elPosition = el.getBoundingClientRect();
524
+ const pagePosition = getPagePosition();
525
+
526
+ return {
527
+ x: parseInt(elPosition.left, BASE) + parseInt(pagePosition.x, BASE),
528
+ y: parseInt(elPosition.top, BASE) + parseInt(pagePosition.y, BASE),
529
+ }
530
+ }
531
+
532
+ function findTarget(location) {
533
+ function jumpToTarget(target) {
534
+ const jumpPosition = getElementPosition(target);
535
+
536
+ sendMsg(jumpPosition.y, jumpPosition.x, 'scrollToOffset'); // X&Y reversed at sendMsg uses height/width
537
+ }
538
+
539
+ const hash = location.split('#')[1] || location; // Remove # if present
540
+ const hashData = decodeURIComponent(hash);
541
+ const target =
542
+ document.getElementById(hashData) ||
543
+ document.getElementsByName(hashData)[0];
544
+
545
+ if (target !== undefined) {
546
+ jumpToTarget(target);
547
+ return
548
+ }
549
+ sendMsg(0, 0, 'inPageLink', `#${hash}`);
550
+ }
551
+
552
+ function checkLocationHash() {
553
+ const { hash, href } = window.location;
554
+
555
+ if (hash !== '' && hash !== '#') {
556
+ findTarget(href);
557
+ }
558
+ }
559
+
560
+ function bindAnchors() {
561
+ function setupLink(el) {
562
+ function linkClicked(e) {
563
+ e.preventDefault();
564
+
565
+ findTarget(this.getAttribute('href'));
566
+ }
567
+
568
+ if (el.getAttribute('href') !== '#') {
569
+ addEventListener(el, 'click', linkClicked);
570
+ }
571
+ }
572
+
573
+ document.querySelectorAll('a[href^="#"]').forEach(setupLink);
574
+ }
575
+
576
+ function bindLocationHash() {
577
+ addEventListener(window, 'hashchange', checkLocationHash);
578
+ }
579
+
580
+ function initCheck() {
581
+ // Check if page loaded with location hash after init resize
582
+ setTimeout(checkLocationHash, eventCancelTimer);
583
+ }
584
+
585
+ function enableInPageLinks() {
586
+ bindAnchors();
587
+ bindLocationHash();
588
+ initCheck();
589
+ }
590
+
591
+ if (inPageLinks.enable) {
592
+ if (mode === 1) {
593
+ advise(
594
+ `In page linking requires a Professional or Business license. Please see https://iframe-resizer.com/pricing for more details.`,
595
+ );
596
+ } else {
597
+ enableInPageLinks();
598
+ }
599
+ }
600
+
601
+ return {
602
+ findTarget,
603
+ }
604
+ }
605
+
606
+ function setupMouseEvents() {
607
+ if (mouseEvents !== true) return
608
+
609
+ function sendMouse(e) {
610
+ sendMsg(0, 0, e.type, `${e.screenY}:${e.screenX}`);
611
+ }
612
+
613
+ function addMouseListener(evt, name) {
614
+ addEventListener(window.document, evt, sendMouse);
615
+ }
616
+
617
+ addMouseListener('mouseenter');
618
+ addMouseListener('mouseleave');
619
+ }
620
+
621
+ function setupPublicMethods() {
622
+ if (mode === 1) return
623
+
624
+ win.parentIframe = Object.freeze({
625
+ autoResize: (resize) => {
626
+ if (resize === true && autoResize === false) {
627
+ autoResize = true;
628
+ startEventListeners();
629
+ } else if (resize === false && autoResize === true) {
630
+ autoResize = false;
631
+ stopEventListeners();
632
+ }
633
+
634
+ sendMsg(0, 0, 'autoResize', JSON.stringify(autoResize));
635
+
636
+ return autoResize
637
+ },
638
+
639
+ close() {
640
+ sendMsg(0, 0, 'close');
641
+ },
642
+
643
+ getId: () => myID,
644
+
645
+ getPageInfo(callback) {
646
+ if (typeof callback === 'function') {
647
+ onPageInfo = callback;
648
+ sendMsg(0, 0, 'pageInfo');
649
+ advise(
650
+ `<rb>Deprecated Method</>
651
+
652
+ The <b>getPageInfo()</> method has been deprecated and replaced with <b>getParentProperties()</>. Use of this method will be removed in a future version of <i>iframe-resizer</>.
653
+ `,
654
+ );
655
+ return
656
+ }
657
+
658
+ onPageInfo = null;
659
+ sendMsg(0, 0, 'pageInfoStop');
660
+ },
661
+
662
+ getParentProperties(callback) {
663
+ if (typeof callback !== 'function') {
664
+ throw new TypeError(
665
+ 'parentIFrame.getParentProperties(callback) callback not a function',
666
+ )
667
+ }
668
+
669
+ onParentInfo = callback;
670
+ sendMsg(0, 0, 'parentInfo');
671
+
672
+ return () => {
673
+ onParentInfo = null;
674
+ sendMsg(0, 0, 'parentInfoStop');
675
+ }
676
+ },
677
+
678
+ moveToAnchor(hash) {
679
+ inPageLinks.findTarget(hash);
680
+ },
681
+
682
+ reset() {
683
+ resetIFrame();
684
+ },
685
+
686
+ scrollTo(x, y) {
687
+ sendMsg(y, x, 'scrollTo'); // X&Y reversed at sendMsg uses height/width
688
+ },
689
+
690
+ scrollToOffset(x, y) {
691
+ sendMsg(y, x, 'scrollToOffset'); // X&Y reversed at sendMsg uses height/width
692
+ },
693
+
694
+ sendMessage(msg, targetOrigin) {
695
+ sendMsg(0, 0, 'message', JSON.stringify(msg), targetOrigin);
696
+ },
697
+
698
+ setHeightCalculationMethod(heightCalculationMethod) {
699
+ heightCalcMode = heightCalculationMethod;
700
+ checkHeightMode();
701
+ },
702
+
703
+ setWidthCalculationMethod(widthCalculationMethod) {
704
+ widthCalcMode = widthCalculationMethod;
705
+ checkWidthMode();
706
+ },
707
+
708
+ setTargetOrigin(targetOrigin) {
709
+ targetOriginDefault = targetOrigin;
710
+ },
711
+
712
+ resize(customHeight, customWidth) {
713
+ const valString = `${customHeight || ''}${customWidth ? `,${customWidth}` : ''}`;
714
+
715
+ sendSize(
716
+ 'size',
717
+ `parentIFrame.size(${valString})`,
718
+ customHeight,
719
+ customWidth,
720
+ );
721
+ },
722
+
723
+ size(customHeight, customWidth) {
724
+ advise(
725
+ `<rb>Deprecated Method</>
726
+
727
+ 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</>.
728
+ `,
729
+ );
730
+ this.resize(customHeight, customWidth);
731
+ },
732
+ });
733
+
734
+ win.parentIFrame = win.parentIframe;
735
+ }
736
+
737
+ let dispatchResized;
738
+
739
+ function resizeObserved(entries) {
740
+ if (!Array.isArray(entries) || entries.length === 0) return
741
+
742
+ const el = entries[0].target;
743
+
744
+ dispatchResized = () =>
745
+ sendSize('resizeObserver', `Resize Observed: ${getElementName(el)}`);
746
+
747
+ // Throttle event to once per current call stack (Safari issue)
748
+ setTimeout(() => {
749
+ if (dispatchResized) dispatchResized();
750
+ dispatchResized = undefined;
751
+ }, 0);
752
+ }
753
+
754
+ const checkPositionType = (element) => {
755
+ const style = getComputedStyle(element);
756
+ return style?.position !== '' && style?.position !== 'static'
757
+ };
758
+
759
+ const getAllNonStaticElements = () =>
760
+ [...getAllElements(document)()].filter(checkPositionType);
761
+
762
+ function setupResizeObservers(el) {
763
+ if (!el) return
764
+ resizeObserver.observe(el);
765
+ }
766
+
767
+ function createResizeObservers(el) {
768
+ [
769
+ ...getAllNonStaticElements(),
770
+ ...resizeObserveTargets.flatMap((target) => el.querySelector(target)),
771
+ ].forEach(setupResizeObservers);
772
+ }
773
+
774
+ function addResizeObservers(mutation) {
775
+ if (mutation.type === 'childList') {
776
+ createResizeObservers(mutation.target);
777
+ }
778
+ }
779
+
780
+ function setupResizeObserver() {
781
+ resizeObserver = new ResizeObserver(resizeObserved);
782
+ createResizeObservers(window.document);
783
+ }
784
+
785
+ function setupBodyMutationObserver() {
786
+ function mutationObserved(mutations) {
787
+ // Look for injected elements that need ResizeObservers
788
+ mutations.forEach(addResizeObservers);
789
+
790
+ // Rebuild elements list for size calculation
791
+ setupCalcElements();
792
+ }
793
+
794
+ function createMutationObserver() {
795
+ const observer = new window.MutationObserver(mutationObserved);
796
+ const target = document.querySelector('body');
797
+ const config = {
798
+ // attributes: true,
799
+ attributes: false,
800
+ attributeOldValue: false,
801
+ // characterData: true,
802
+ characterData: false,
803
+ characterDataOldValue: false,
804
+ childList: true,
805
+ subtree: true,
806
+ };
807
+ observer.observe(target, config);
808
+
809
+ return observer
810
+ }
811
+
812
+ const observer = createMutationObserver();
813
+
814
+ return {
815
+ disconnect() {
816
+ observer.disconnect();
817
+ },
818
+ }
819
+ }
820
+
821
+ function setupMutationObserver() {
822
+ bodyObserver = setupBodyMutationObserver();
823
+ }
824
+
825
+ function getMaxElement(side) {
826
+ const Side = capitalizeFirstLetter(side);
827
+
828
+ let elVal = 0;
829
+ let len = calcElements.length;
830
+ let maxEl;
831
+ let maxVal = 0;
832
+ let timer = performance.now();
833
+
834
+ calcElements.forEach((element) => {
835
+ if (
836
+ !hasTags &&
837
+ hasCheckVisibility &&
838
+ !element.checkVisibility(checkVisibilityOptions)
839
+ ) {
840
+ len -= 1;
841
+ return
842
+ }
843
+
844
+ elVal =
845
+ element.getBoundingClientRect()[side] +
846
+ parseFloat(getComputedStyle(element).getPropertyValue(`margin-${side}`));
847
+
848
+ if (elVal > maxVal) {
849
+ maxVal = elVal;
850
+ maxEl = element;
851
+ }
852
+ });
853
+
854
+ timer = performance.now() - timer;
855
+
856
+ const logMsg = `
857
+ Parsed ${len} element${(len = '' )} in ${timer.toPrecision(3)}ms
858
+ ${Side} ${hasTags ? 'tagged ' : ''}element found at: ${maxVal}px
859
+ Position calculated from HTML element: ${elementSnippet(maxEl)}`;
860
+
861
+ if (timer < 1.1 || isInit || hasTags) ; else {
862
+ advise(
863
+ `<rb>Performance Warning</>
864
+
865
+ Calculating the page size took an excessive amount of time. To improve performance add the <b>data-iframe-size</> attribute to the ${side} most element on the page.
866
+ ${logMsg}`,
867
+ );
868
+ }
869
+ return maxVal
870
+ }
871
+
872
+ const getAllMeasurements = (dimension) => [
873
+ dimension.bodyOffset(),
874
+ dimension.bodyScroll(),
875
+ dimension.documentElementOffset(),
876
+ dimension.documentElementScroll(),
877
+ dimension.documentElementBoundingClientRect(),
878
+ ];
879
+
880
+ const getAllElements = (element) => () =>
881
+ element.querySelectorAll(
882
+ '* :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)',
883
+ );
884
+
885
+ let switchChecked = false;
886
+
887
+ function switchToAutoOverflow({
888
+ ceilBoundingSize,
889
+ dimension,
890
+ getDimension,
891
+ isHeight,
892
+ scrollSize,
893
+ }) {
894
+ if (!switchChecked) {
895
+ // If this just happens once, then it is likely we just came from a large page.
896
+ switchChecked = true;
897
+ return getDimension.taggedElement()
898
+ }
899
+
900
+ const furthest = isHeight ? 'lowest' : 'right most';
901
+ const side = isHeight ? 'bottom' : 'right';
902
+ const overflowDetectedMessage = `<rb>Detected content overflowing html element</>
903
+
904
+ This causes <i>iframe-resizer</> to fall back to checking the position of every element on the page in order to calculate the correct dimensions of the iframe. Inspecting the size, ${side} margin, and position of every visible HTML element will have a performance impact on more complex pages.
905
+
906
+ To fix this issue, and remove this warning, you can either ensure the content of the page does not overflow the <b><HTML></> element or alternatively you can add the attribute <b>data-iframe-size</> to the elements on the page that you want <i>iframe-resizer</> to use when calculating the dimensions of the iframe.
907
+
908
+ When present the <i>${side} margin of the ${furthest} element</> with a <b>data-iframe-size</> attribute will be used to set the ${dimension} of the iframe.
909
+
910
+ (Page size: ${scrollSize} > document size: ${ceilBoundingSize})`;
911
+
912
+ advise(overflowDetectedMessage);
913
+
914
+ if (isHeight) {
915
+ heightCalcMode = 'autoOverflow';
916
+ } else {
917
+ widthCalcMode = 'autoOverflow';
918
+ }
919
+
920
+ return getDimension.taggedElement()
921
+ }
922
+
923
+ const prevScrollSize = {
924
+ height: 0,
925
+ width: 0,
926
+ };
927
+
928
+ const prevBoundingSize = {
929
+ height: 0,
930
+ width: 0,
931
+ };
932
+
933
+ const getAdjustedScroll = (getDimension) =>
934
+ getDimension.documentElementScroll() + Math.max(0, getDimension.getOffset());
935
+
936
+ function getAutoSize(getDimension, autoOverflow) {
937
+ function returnBoundingClientRect() {
938
+ prevBoundingSize[dimension] = boundingSize;
939
+ prevScrollSize[dimension] = scrollSize;
940
+ return boundingSize
941
+ }
942
+
943
+ const isHeight = getDimension === getHeight;
944
+ const dimension = isHeight ? 'height' : 'width';
945
+ const boundingSize = getDimension.documentElementBoundingClientRect();
946
+ const ceilBoundingSize = Math.ceil(boundingSize);
947
+ const floorBoundingSize = Math.floor(boundingSize);
948
+ const scrollSize = getAdjustedScroll(getDimension);
949
+
950
+ switch (true) {
951
+ case !getDimension.enabled():
952
+ return scrollSize
953
+
954
+ case !autoOverflow &&
955
+ prevBoundingSize[dimension] === 0 &&
956
+ prevScrollSize[dimension] === 0:
957
+ if (getDimension.taggedElement(true) <= ceilBoundingSize) {
958
+ return returnBoundingClientRect()
959
+ }
960
+ break
961
+
962
+ case triggerLocked &&
963
+ boundingSize === prevBoundingSize[dimension] &&
964
+ scrollSize === prevScrollSize[dimension]:
965
+ return Math.max(boundingSize, scrollSize)
966
+
967
+ case boundingSize === 0:
968
+ return scrollSize
969
+
970
+ case !autoOverflow &&
971
+ boundingSize !== prevBoundingSize[dimension] &&
972
+ scrollSize <= prevScrollSize[dimension]:
973
+ return returnBoundingClientRect()
974
+
975
+ case !isHeight:
976
+ return autoOverflow
977
+ ? getDimension.taggedElement()
978
+ : switchToAutoOverflow({
979
+ ceilBoundingSize,
980
+ dimension,
981
+ getDimension,
982
+ isHeight,
983
+ scrollSize,
984
+ })
985
+
986
+ case !autoOverflow && boundingSize < prevBoundingSize[dimension]:
987
+ return returnBoundingClientRect()
988
+
989
+ case scrollSize === floorBoundingSize || scrollSize === ceilBoundingSize:
990
+ return returnBoundingClientRect()
991
+
992
+ case boundingSize > scrollSize:
993
+ return returnBoundingClientRect()
994
+
995
+ case !autoOverflow:
996
+ return switchToAutoOverflow({
997
+ ceilBoundingSize,
998
+ dimension,
999
+ getDimension,
1000
+ isHeight,
1001
+ scrollSize,
1002
+ })
1003
+ }
1004
+
1005
+ return Math.max(getDimension.taggedElement(), returnBoundingClientRect())
1006
+ }
1007
+
1008
+ const getBodyOffset = () => {
1009
+ const { body } = document;
1010
+ const style = getComputedStyle(body);
1011
+
1012
+ return (
1013
+ body.offsetHeight +
1014
+ parseInt(style.marginTop, BASE) +
1015
+ parseInt(style.marginBottom, BASE)
1016
+ )
1017
+ };
1018
+
1019
+ const getHeight = {
1020
+ enabled: () => calculateHeight,
1021
+ getOffset: () => offsetHeight,
1022
+ type: 'height',
1023
+ auto: () => getAutoSize(getHeight, false),
1024
+ autoOverflow: () => getAutoSize(getHeight, true),
1025
+ bodyOffset: getBodyOffset,
1026
+ bodyScroll: () => document.body.scrollHeight,
1027
+ offset: () => getHeight.bodyOffset(), // Backwards compatibility
1028
+ custom: () => customCalcMethods.height(),
1029
+ documentElementOffset: () => document.documentElement.offsetHeight,
1030
+ documentElementScroll: () => document.documentElement.scrollHeight,
1031
+ documentElementBoundingClientRect: () =>
1032
+ document.documentElement.getBoundingClientRect().bottom,
1033
+ max: () => Math.max(...getAllMeasurements(getHeight)),
1034
+ min: () => Math.min(...getAllMeasurements(getHeight)),
1035
+ grow: () => getHeight.max(),
1036
+ lowestElement: () => getMaxElement('bottom'),
1037
+ taggedElement: () => getMaxElement('bottom'),
1038
+ };
1039
+
1040
+ const getWidth = {
1041
+ enabled: () => calculateWidth,
1042
+ getOffset: () => offsetWidth,
1043
+ type: 'width',
1044
+ auto: () => getAutoSize(getWidth, false),
1045
+ autoOverflow: () => getAutoSize(getWidth, true),
1046
+ bodyScroll: () => document.body.scrollWidth,
1047
+ bodyOffset: () => document.body.offsetWidth,
1048
+ custom: () => customCalcMethods.width(),
1049
+ documentElementScroll: () => document.documentElement.scrollWidth,
1050
+ documentElementOffset: () => document.documentElement.offsetWidth,
1051
+ documentElementBoundingClientRect: () =>
1052
+ document.documentElement.getBoundingClientRect().right,
1053
+ max: () => Math.max(...getAllMeasurements(getWidth)),
1054
+ min: () => Math.min(...getAllMeasurements(getWidth)),
1055
+ rightMostElement: () => getMaxElement('right'),
1056
+ scroll: () =>
1057
+ Math.max(getWidth.bodyScroll(), getWidth.documentElementScroll()),
1058
+ taggedElement: () => getMaxElement('right'),
1059
+ };
1060
+
1061
+ function sizeIFrame(
1062
+ triggerEvent,
1063
+ triggerEventDesc,
1064
+ customHeight,
1065
+ customWidth,
1066
+ msg,
1067
+ ) {
1068
+ function resizeIFrame() {
1069
+ height = currentHeight;
1070
+ width = currentWidth;
1071
+ sendMsg(height, width, triggerEvent, msg);
1072
+ }
1073
+
1074
+ function isSizeChangeDetected() {
1075
+ const checkTolerance = (a, b) => !(Math.abs(a - b) <= tolerance);
1076
+
1077
+ // currentHeight = Math.ceil(
1078
+ // undefined === customHeight ? getHeight[heightCalcMode]() : customHeight,
1079
+ // )
1080
+
1081
+ // currentWidth = Math.ceil(
1082
+ // undefined === customWidth ? getWidth[widthCalcMode]() : customWidth,
1083
+ // )
1084
+
1085
+ currentHeight =
1086
+ undefined === customHeight ? getHeight[heightCalcMode]() : customHeight;
1087
+ currentWidth =
1088
+ undefined === customWidth ? getWidth[widthCalcMode]() : customWidth;
1089
+
1090
+ return (
1091
+ (calculateHeight && checkTolerance(height, currentHeight)) ||
1092
+ (calculateWidth && checkTolerance(width, currentWidth))
1093
+ )
1094
+ }
1095
+
1096
+ const isForceResizableEvent = () => !(triggerEvent in { init: 1, size: 1 });
1097
+
1098
+ const isForceResizableCalcMode = () =>
1099
+ (calculateHeight && heightCalcMode in resetRequiredMethods) ||
1100
+ (calculateWidth && widthCalcMode in resetRequiredMethods);
1101
+
1102
+ function checkDownSizing() {
1103
+ if (isForceResizableEvent() && isForceResizableCalcMode()) {
1104
+ resetIFrame();
1105
+ }
1106
+ }
1107
+
1108
+ let currentHeight;
1109
+ let currentWidth;
1110
+
1111
+ if (isSizeChangeDetected() || triggerEvent === 'init') {
1112
+ lockTrigger();
1113
+ resizeIFrame();
1114
+ } else {
1115
+ checkDownSizing();
1116
+ }
1117
+ }
1118
+
1119
+ function sendSize(
1120
+ triggerEvent,
1121
+ triggerEventDesc,
1122
+ customHeight,
1123
+ customWidth,
1124
+ msg,
1125
+ ) {
1126
+ if (document.hidden) {
1127
+ // Currently only correctly supported in firefox
1128
+ // This is checked again on the parent page
1129
+ return
1130
+ }
1131
+
1132
+ sizeIFrame(triggerEvent, triggerEventDesc, customHeight, customWidth, msg);
1133
+ }
1134
+
1135
+ function lockTrigger() {
1136
+ if (triggerLocked) return
1137
+
1138
+ triggerLocked = true;
1139
+
1140
+ requestAnimationFrame(() => {
1141
+ triggerLocked = false;
1142
+ });
1143
+ }
1144
+
1145
+ function triggerReset(triggerEvent) {
1146
+ height = getHeight[heightCalcMode]();
1147
+ width = getWidth[widthCalcMode]();
1148
+
1149
+ sendMsg(height, width, triggerEvent);
1150
+ }
1151
+
1152
+ function resetIFrame(triggerEventDesc) {
1153
+ const hcm = heightCalcMode;
1154
+ heightCalcMode = heightCalcModeDefault;
1155
+ lockTrigger();
1156
+ triggerReset('reset');
1157
+
1158
+ heightCalcMode = hcm;
1159
+ }
1160
+
1161
+ function sendMsg(height, width, triggerEvent, msg, targetOrigin) {
1162
+ if (mode < 0) return
1163
+
1164
+ function setTargetOrigin() {
1165
+ if (undefined === targetOrigin) {
1166
+ targetOrigin = targetOriginDefault;
1167
+ return
1168
+ }
1169
+ }
1170
+
1171
+ function sendToParent() {
1172
+ const size = `${height + (offsetHeight || 0)}:${width + (offsetWidth || 0)}`;
1173
+ const message = `${myID}:${size}:${triggerEvent}${undefined === msg ? '' : `:${msg}`}`;
1174
+
1175
+ if (sameDomain) {
1176
+ window.parent.iframeParentListener(msgID + message);
1177
+ return
1178
+ }
1179
+
1180
+ target.postMessage(msgID + message, targetOrigin);
1181
+ }
1182
+
1183
+ setTargetOrigin();
1184
+ sendToParent();
1185
+ }
1186
+
1187
+ function receiver(event) {
1188
+ const processRequestFromParent = {
1189
+ init: function initFromParent() {
1190
+ initMsg = event.data;
1191
+ target = event.source;
1192
+
1193
+ init();
1194
+ firstRun = false;
1195
+ setTimeout(() => {
1196
+ initLock = false;
1197
+ }, eventCancelTimer);
1198
+ },
1199
+
1200
+ reset() {
1201
+ if (initLock) {
1202
+ return
1203
+ }
1204
+ triggerReset('resetPage');
1205
+ },
1206
+
1207
+ resize() {
1208
+ sendSize('resizeParent', 'Parent window requested size check');
1209
+ },
1210
+
1211
+ moveToAnchor() {
1212
+ inPageLinks.findTarget(getData());
1213
+ },
1214
+
1215
+ inPageLink() {
1216
+ this.moveToAnchor();
1217
+ }, // Backward compatibility
1218
+
1219
+ pageInfo() {
1220
+ const msgBody = getData();
1221
+ if (onPageInfo) {
1222
+ onPageInfo(JSON.parse(msgBody));
1223
+ } else {
1224
+ // not expected, so cancel more messages
1225
+ sendMsg(0, 0, 'pageInfoStop');
1226
+ }
1227
+ },
1228
+
1229
+ parentInfo() {
1230
+ const msgBody = getData();
1231
+ if (onParentInfo) {
1232
+ onParentInfo(Object.freeze(JSON.parse(msgBody)));
1233
+ } else {
1234
+ // not expected, so cancel more messages
1235
+ sendMsg(0, 0, 'parentInfoStop');
1236
+ }
1237
+ },
1238
+
1239
+ message() {
1240
+ const msgBody = getData();
1241
+ // eslint-disable-next-line sonarjs/no-extra-arguments
1242
+ onMessage(JSON.parse(msgBody));
1243
+ },
1244
+ };
1245
+
1246
+ const isMessageForUs = () => msgID === `${event.data}`.slice(0, msgIdLen);
1247
+
1248
+ const getMessageType = () => event.data.split(']')[1].split(':')[0];
1249
+
1250
+ const getData = () => event.data.slice(event.data.indexOf(':') + 1);
1251
+
1252
+ const isMiddleTier = () =>
1253
+ 'iframeResize' in window ||
1254
+ (window.jQuery !== undefined && '' in window.jQuery.prototype);
1255
+
1256
+ // Test if this message is from a child below us. This is an ugly test, however, updating
1257
+ // the message format would break backwards compatibility.
1258
+ const isInitMsg = () => event.data.split(':')[2] in { true: 1, false: 1 };
1259
+
1260
+ function callFromParent() {
1261
+ const messageType = getMessageType();
1262
+
1263
+ if (messageType in processRequestFromParent) {
1264
+ processRequestFromParent[messageType]();
1265
+ return
1266
+ }
1267
+
1268
+ if (!isMiddleTier() && !isInitMsg()) {
1269
+ warn(`Unexpected message (${event.data})`);
1270
+ }
1271
+ }
1272
+
1273
+ function processMessage() {
1274
+ if (firstRun === false) {
1275
+ callFromParent();
1276
+ return
1277
+ }
1278
+
1279
+ if (isInitMsg()) {
1280
+ processRequestFromParent.init();
1281
+ return
1282
+ }
1283
+ }
1284
+
1285
+ if (isMessageForUs()) {
1286
+ processMessage();
1287
+ }
1288
+ }
1289
+
1290
+ // Normally the parent kicks things off when it detects the iFrame has loaded.
1291
+ // If this script is async-loaded, then tell parent page to retry init.
1292
+ function chkLateLoaded() {
1293
+ if (document.readyState !== 'loading') {
1294
+ window.parent.postMessage('[iFrameResizerChild]Ready', '*');
1295
+ }
1296
+ }
1297
+
1298
+ // Don't run for server side render
1299
+ if (typeof window !== 'undefined') {
1300
+ window.iframeChildListener = (data) => receiver({ data, sameDomain: true });
1301
+ addEventListener(window, 'message', receiver);
1302
+ addEventListener(window, 'readystatechange', chkLateLoaded);
1303
+ chkLateLoaded();
1304
+ }