Skip to content

Instantly share code, notes, and snippets.

@yoya
Last active October 24, 2023 08:29
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 yoya/380deec271488c7f3d3ff9a2ada6ac3c to your computer and use it in GitHub Desktop.
Save yoya/380deec271488c7f3d3ff9a2ada6ac3c to your computer and use it in GitHub Desktop.
iframe postmessage bidirect
<html>
<body>
<div>
This is iframe
</div>
<script>
const origin = location.origin;
window.onload = () => {
window.addEventListener("message", (resp) => {
console.log("iframe", resp)
const blob = resp.data.get("blob");
const parentWindow = window.parent;
const map = new Map();
map.set('blob',blob);
parentWindow.postMessage(map, origin);
})
};
</script>
</body>
</html>
<html>
<body>
<div>
this is parent page
<iframe id="iframe" src="iframe.html"> </iframe>
</div>
<script>
const origin = location.origin;
window.onload = () => {
console.log("index.html")
const imgsrc = "./test.jpg";
const image = new Image()
image.src = imgsrc;
image.onload = () => {
     const c = document.createElement("canvas");
                         const ctx = c.getContext("2d");
                         c.width = image.naturalWidth;
                         c.height = image.naturalHeight;
                         ctx.drawImage(image, 0, 0);
                         c.toBlob( (blob) => {
                             const map = new Map();
                             map.set('blob', blob);
iframe.contentWindow.postMessage(map, origin);
     }, "image/jpeg")
     }
     window.addEventListener('message', (resp) => {
     console.log("parent", resp);
     });
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment