-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiframeComListener.js
48 lines (44 loc) · 1.19 KB
/
iframeComListener.js
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
document.addEventListener('DOMContentLoaded', function () {
const iframe = document.getElementById("iframe");
if (!iframe) return console.warn('No iFrame with ID of "iframe"')
window.addEventListener('message', (e) => {
const messageType = e.data.type;
switch (messageType) {
case "resize":
iframe.style.minHeight = `${e.data.data.height + 50}px`;
break;
case "location":
window.scroll(0, iframe.offsetTop);
break;
case "redirect":
const redirectUrl = e.data.redirectUrl;
if (!redirectUrl) {
break;
}
window.location.replace(redirectUrl)
break;
case "settings":
if (e.data.data.state === "initial") {
setInitialSettings(iframe, e.data);
}
}
});
const setInitialSettings = (
iframe,
e
) => {
const background = iframe.getAttribute("data-background-color");
if (background) {
const message = {
type: "background",
data: {
background,
},
};
iframe.contentWindow.postMessage(message, "*");
}
if (e.data.height) {
iframe.style.minHeight = `${e.data.height + 50}px`;
}
};
});