2

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.
Krupal Panchal
  • 1,553
  • 2
  • 13
  • 26
MetaTron
  • 895
  • 9
  • 14

2 Answers2

1

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>
MetaTron
  • 895
  • 9
  • 14
  • Thanks for this simple example. Totally agree with you about it being over-engineered. Gives me a headache to read the W3 recommendation. – Steven de Salas Sep 23 '20 at 10:29
0

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

furkeen
  • 411
  • 5
  • 11