8

I have the iframe:

<iframe id="GameFrame" 
sandbox="allow-scripts allow-pointer-lock" 
src="https://127.0.0.1:112/games/1047/play">
</iframe>

My parent page is located at:

https://127.0.0.1/arcade/not-hidden/space-blaster-1047

I'm trying to post a message to the iFrame:

var gameIframe = $("#GameFrame");
gameIframe.get(0).contentWindow.postMessage("screenshot", "");

But this throws the error:

Uncaught SyntaxError: Failed to execute 'postMessage' on 'Window': Invalid target origin '' in a call to 'postMessage'.

Other attempts:

postMessage("screenshot", "https://127.0.0.1");

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://127.0.0.1') does not match the recipient window's origin ('null').

How can I get this posting a message to the iFrame?

Tom Gullen
  • 61,249
  • 84
  • 283
  • 456
  • This looks like a duplicate. See: http://stackoverflow.com/questions/23373376/uncaught-syntaxerror-failed-to-execute-postmessage-on-window-invalid-targe – theUtherSide Sep 14 '15 at 23:46

2 Answers2

5

Just figured this out right now, need to use * as the origin:

gameIframe.get(0).contentWindow.postMessage("screenshot", "*");
Tom Gullen
  • 61,249
  • 84
  • 283
  • 456
  • 3
    Be aware of the dangers of using "*" for the target. This allows any JS to receieve the message by implementing `addEventListener('message'...)`. MDN has details on how to securely use `postMessage`. https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage – theUtherSide Sep 14 '15 at 23:39
  • 1
    I am getting "Protocols, domains, and ports must match" error on Safari, even though I postMessage to * target origin. Other browsers work. Is wildcard target not supported by Safari? What could be the reason? – fiatux Dec 20 '17 at 22:11
3

I got this error when I run the code locally (in a local directory), but when I put it in a webserver (Tomcat), the code works.

Marvin
  • 853
  • 2
  • 14
  • 38