How To Call Host From Iframe Cross-Origin Communication

by Owais Mushtaq

Window.postMessage method safely enables cross-origin communication. Normally, scripts on different pages are allowed to access each other if and only if the pages that execute them are at locations with the same protocol (usually both https), port number (443 being the default for https), and host (modulo document.domain being set by both pages to the same value). Window.postMessage provides a controlled mechanism to circumvent this restriction in a way which is secure when properly used.

The code in an iframe: window.postMessage(message, targetOrigin);

message: the message to be send

targetOrigin: Specifies the origin of otherWindow in same protocol, the origin must be for the event to be dispatched, either as the literal string ‘*’ that specifies no preference or can be a url.

like window.postMessage(message,’*’ );

 

The code in parent window:

window.addEventListener(‘message’, receiveMessage, false);

function receiveMessage(evt)

{

  $.ajax({

          type: “GET”,

          url: ‘/dashboard/documents/notify_count’,

          async: false,

          data: {},

          success:function(response) {

              window.onbeforeunload = null;

              window.location.href = “url”;

          }

      });

}

The above method is once called from an iframe, the action takes place at the parent window/host, in this case the action is to redirect the window to a specific url.

This is a quick example of cross-origin communication/messaging within different hosts. Looking forward for questions?

Leave a Reply

Your email address will not be published. Required fields are marked *

Tools & Practices

Tools and Technologies we use at Applied

Contact us now

Popular Posts