Skip to content

Instantly share code, notes, and snippets.

@andersevenrud
Created July 27, 2020 22:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andersevenrud/f6b5dd6bb62c456c13ab4b7652a90c52 to your computer and use it in GitHub Desktop.
Save andersevenrud/f6b5dd6bb62c456c13ab4b7652a90c52 to your computer and use it in GitHub Desktop.
PoC to do bi-directional communiction between a parent and iframe document
<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>
<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