Failed to execute 'postMessage' on 'Window': Invalid target origin

26,842

Solution 1

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

gameIframe.get(0).contentWindow.postMessage("screenshot", "*");

Solution 2

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.

Share:
26,842
Tom Gullen
Author by

Tom Gullen

Me Web developer. Website http://www.scirra.com

Updated on September 03, 2020

Comments

  • Tom Gullen
    Tom Gullen over 3 years

    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?

  • theUtherSide
    theUtherSide over 8 years
    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. developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
  • fiatux
    fiatux over 6 years
    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?