-
Notifications
You must be signed in to change notification settings - Fork 0
/
getResizeScript.ts
54 lines (51 loc) · 1.77 KB
/
getResizeScript.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { HEIGHT_MESSAGE, POST_MESSAGE_IDENTIFIER } from "./constants";
import { SeamlessIframeProps } from "./definitions";
export const renderResizeScript = (
id: number,
props: Pick<
SeamlessIframeProps,
"heightCorrection" | "heightCorrectionOnResize" | "debounceResizeTime"
>
) => {
if (!props.heightCorrection) {
return "";
}
let output = `
const validatedMessage = () => JSON.stringify("${POST_MESSAGE_IDENTIFIER}///${id}///${HEIGHT_MESSAGE}///"+document.documentElement.offsetHeight);
window.__seamlessHeightLoad = () => parent.postMessage(validatedMessage(), "${window.location.href}");
window.addEventListener("load", window.__seamlessHeightLoad);
`;
if (!props.heightCorrectionOnResize) {
return output;
}
if (props.debounceResizeTime) {
output += `
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
window.__seamlessHeightResize = debounce(() => {
parent.postMessage(validatedMessage(), "${window.location.href}")
}, ${props.debounceResizeTime});
`;
} else {
output += `
window.__seamlessHeightResize = () => {
parent.postMessage(validatedMessage(), "${window.location.href}")
};
`;
}
return (
output + `window.addEventListener("resize", window.__seamlessHeightResize);`
);
};