I need to receive data from cross-origin iframe. The Iframe content website is also mine. Everybody says that postMessage() works in both directions, but not for me.
If anybody has some experience about my problem, I'll be very grateful:)
in iframe's website code
window.postMessage("ehooo!", "*");
in website code
<iframe src="https://ehooo.com" name="iframe" onLoad="iframeLoaded()"></iframe>
<script>
function iframeLoaded() {
event.target.contentWindow.addEventListener("message", e => {
console.log(e.data);
});
}
</script>
the console output
Uncaught DOMException: Blocked a frame with origin "https://ehooo.com" from accessing a cross-origin frame.
Okay guys, I figured out. So before I was asking the iframe to give me the message instead of the window. I was doing it because the window was giving me nothing. It looks like if you are sending from iframe to parent we need to set postMessage to parent and to ask for the message in to the window object. I've got it from ( here ) a bit complicated and over engineered but gave me the right clue.
in iframe code
window.parent.postMessage("ehooo!", "*");
in website code
<iframe src="https://ehooo.com" name="iframe"></iframe>
<script>
window.addEventListener("message", e => console.log(e.data));
</script>
You should give permission from iframe website to iframe reciever website with .htaccess file
# Sets CORS headers for request from example1.com and example2.com pages
# for both SSL and non-SSL
SetEnvIf Origin "^https?://[^/]*(reciverewebsite)\.com$" ORIGIN=$0
Header set Access-Control-Allow-Origin %{ORIGIN}e env=ORIGIN
Header set Access-Control-Allow-Credentials "true" env=ORIGIN
# Always set Vary: Origin when it's possible you may send CORS headers
Header merge Vary Origin
it is worked for my project
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.