Last active
January 27, 2024 23:14
-
-
Save mbajur/8325540 to your computer and use it in GitHub Desktop.
Working example of window.postMessage used for sending data from popup to parent page (works in IE)
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 lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Index</title> | |
<script type="text/javascript"> | |
window.open ("popup.html","mywindow", "width=350,height=250"); | |
// Create IE + others compatible event handler | |
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent"; | |
var eventer = window[eventMethod]; | |
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message"; | |
// Listen to message from child window | |
eventer(messageEvent,function(e) { | |
console.log('origin: ', e.origin) | |
// Check if origin is proper | |
if( e.origin != 'http://localhost' ){ return } | |
console.log('parent received message!: ', e.data); | |
}, false); | |
</script> | |
</head> | |
<body> | |
</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
<!doctype html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Popup</title> | |
</head> | |
<body> | |
<script type="text/javascript"> | |
window.opener.postMessage({token: 'aaa', secret: 'bbb'}, 'http://localhost'); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I came across this when searching for getting post message to work cross domains using a popup in IE11. The solution in this code didn't work for me in IE11, but a very similar solution that I found on SO did:
https://stackoverflow.com/a/36630058/2754718
In case for whatever reason that link breaks in the future, here is what it said:
Building on answer by tangle, I had success in IE11 [and emulated IE10 mode] using following snippet:
Then I was able to communicate using typical postMessage stack, I'm using one global static messenger in my scenario (alotough I don't suppose it's of any signifficance, I'm also attaching my messenger class)
No matter how hard I tried, I wasn't able to make things work on IE9 and IE8
My config where it's working:
IE version: 11.0.10240.16590, Update versions: 11.0.25 (KB3100773)