Last active
January 6, 2024 23:02
-
Star
(123)
You must be signed in to star a gist -
Fork
(39)
You must be signed in to fork a gist
-
-
Save cirocosta/9f730967347faf9efb0b to your computer and use it in GitHub Desktop.
Sending messages from child iframe to parent webpage
This file contains hidden or 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> | |
<title>My Iframe</title> | |
</head> | |
<body> | |
<button>Botão</button> | |
<script type="text/javascript"> | |
document.querySelector('button').onclick = function () { | |
// parent.postMessage("message to be sent", "http://the-website-that-will-receive-the-msg.com") | |
parent.postMessage("myevent", "*") | |
}; | |
</script> | |
</body> | |
</html> |
This file contains hidden or 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> | |
<title>Index</title> | |
</head> | |
<body> | |
<iframe src="iframe.html" width="300" height="300"></iframe> | |
<script type="text/javascript"> | |
var eventMethod = window.addEventListener | |
? "addEventListener" | |
: "attachEvent"; | |
var eventer = window[eventMethod]; | |
var messageEvent = eventMethod === "attachEvent" | |
? "onmessage" | |
: "message"; | |
eventer(messageEvent, function (e) { | |
// if (e.origin !== 'http://the-trusted-iframe-origin.com') return; | |
if (e.data === "myevent" || e.message === "myevent") | |
alert('Message from iframe just came!'); | |
console.log(e); | |
}); | |
</script> | |
</body> | |
</html> |
Works perfectly! I didn't know parent
can be used as global variable, like this
are.
Thank you so much! Saved the day!
Perfect, it really works :)
Niceeeeeeeeeeeeee
Thank you!
thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I believe you can try and use the main page to ask the user media access, and retrieve the IDs, then you can send the IDs to the iframe via a message and use it there.
Of course you need to make sure the Iframe is also under SSL because otherwise it wouldn't work..