Skip to content

Instantly share code, notes, and snippets.

@acdcjunior
Created August 22, 2019 00:57
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 acdcjunior/0d309f1dcf2ba3f0be996e65d37a58f5 to your computer and use it in GitHub Desktop.
Save acdcjunior/0d309f1dcf2ba3f0be996e65d37a58f5 to your computer and use it in GitHub Desktop.
iframe window.postMessage example (inter-frame CORS communication)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>5051</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.js"></script>
</head>
<body>
<h1>5051</h1>
<button id="go">GO</button>
<script>
$("#go").click(() => {
let win = window.top;
win.postMessage("from 5051 to top", "*");
})
</script>
<br>
<pre id="out"></pre>
<script>
window.addEventListener("message", e => {
//debugger;
$("#out").text((_, t) => `${t}\n${e.data}`)
});
</script>
</body>
</html>
<!-- can also message back using e.source.postMessage(...) -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>5050</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.js"></script>
</head>
<body>
<h1>5050</h1>
<button id="go">GO</button>
<script>
$("#go").click(() => {
let win = window.frames.bobnelson5051;
win.postMessage("from 5050 to 5051", "*");
});
</script>
<br>
<iframe src="http://localhost:5051/5051.html" name="bobnelson5051" height=500></iframe>
<pre id="out"></pre>
<script>
top.addEventListener("message", e => {
//debugger;
$("#out").text((_, t) => `${t}\n${e.data}`)
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment