Created
August 22, 2019 00:57
-
-
Save acdcjunior/0d309f1dcf2ba3f0be996e65d37a58f5 to your computer and use it in GitHub Desktop.
iframe window.postMessage example (inter-frame CORS communication)
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
<!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(...) --> |
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
<!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