Search code examples
javascriptjqueryiframepostmessage

How to target an element outside an iframe with different protocol using Javascript postMessage


I have a button in an iframe and I wish that, it triggers another button, which is found outside the iframe, when clicked.

Here is a piece of code that I have been trying to work out.

The HTML

<body>
 <iframe id="layer-frame" src="https://somepage.com">
  <a href="https://page2.com" target="_blank" id="js-gopage2" class="js-iframepostmsg" alt="CLICK HERE TO Edit your profile">Edit your profile</a>
 </iframe>
 <div>
  <a class="close" href="#">Close<span></span></a>
 </div>
</body>

in Parent html

window.addEventListener("message", receiveMessage, false);

function receiveMessage(event)
{
 if(event.data == "click!") {
  $('a.close').trigger('click');
 }
}

in iframe

var targetOrigin = window.location.host;
top.window.postMessage("click!", targetOrigin);

Solution

  • targetOrigin = window.location.host is going to give you the hostname of the page you are posting from but:

    targetOrigin
    Specifies what the origin of otherWindow must be for the event to be dispatched

    and

    the scheme, hostname, or port of otherWindow's document does not match that provided in targetOrigin

    so you need to provide a complete origin (such as http://example.com:234), not just the hostname.

    If you don't care which origin is allowed to read the message, use "*".