Created
July 27, 2020 22:31
-
-
Save andersevenrud/f6b5dd6bb62c456c13ab4b7652a90c52 to your computer and use it in GitHub Desktop.
PoC to do bi-directional communiction between a parent and iframe document
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<body> | |
<img id="image" /> | |
<script> | |
const image = document.getElementById('image') | |
const postMessage = (data) => { | |
top.postMessage(JSON.stringify(data), '*') | |
} | |
const handleMessage = (data) => { | |
switch (data.action) { | |
case 'update image': | |
image.src = data.args[0] | |
break; | |
} | |
} | |
image.addEventListener('load', () => { | |
postMessage({ | |
action: 'image loaded' | |
}) | |
}) | |
window.addEventListener('message', (ev) => { | |
const data = JSON.parse(ev.data) | |
handleMessage(data) | |
}) | |
</script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
</head> | |
<body> | |
<iframe id="iframe"></iframe> | |
<button type="button" id="button">Update Image</button> | |
<script> | |
const iframe = document.getElementById('iframe') | |
const button = document.getElementById('button') | |
const handleMessage = (data) => { | |
switch (data.action) { | |
case 'image loaded': | |
alert('Image loaded') | |
break; | |
} | |
} | |
const postMessage = (data) => { | |
iframe.contentWindow.postMessage(JSON.stringify(data), window.location.href) | |
} | |
window.addEventListener('message', (ev) => { | |
const data = JSON.parse(ev.data) | |
handleMessage(data) | |
}) | |
button.addEventListener('click', () => { | |
postMessage({ | |
action: 'update image', | |
args: ['http://path/to/image.jpeg'] | |
}, window.location.href) | |
}) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment