Post to IFRAME

Sometimes there is the need to embed some site inside another and an IFrame because a necessary evil.

But then there is the need to comunicate the two sites.

A common need is to send credential from one site to the other.

How can that be achieved??

Well after searching the web. I found that there are many alternatives.

  1. Sending messages.

Frames are mostly like separate windows. However you can still comunicate between them.

The api is simple. The page that hosts the iframe needs a reference to iframe element and can then just post any string or json.

    //select the iframe containing the message receiver remote script
    var remoteframe = document.getElementById("remotepage");
    var message = "some message"
    remoteframe.contentWindow.postMessage(message, 'http://fiddle.jshell.net');

The receiving frame needs to susbcribe a message listener and should validate the message origin for safety:

  //This function is called whenever the window receives a message event, the message object is passed in as it's only parameter

function receiver(message) {  
    var trusteddomain = "http://fiddle.jshell.net";

    //use the origin property of the message event to 
    //ensure the message originates from the same domain)
      if (message.origin == trusteddomain) {
        //Do your accions.
      }
    }

//Add an event listener to the window object to catch any message events
window.addEventListener('message', receiver, false);  

You can see a working example at: http://jsfiddle.net/Orellabac/9z3hqfsj/2/
The source for the receiving frame is at:
http://fiddle.jshell.net/eopbv3sp/2/

  1. Post to IFRAME

Another simple option is to post directly to the iframe:

You can do something like:

<form ... target="my_iframe">  
...
</form>

<iframe name="my_iframe" ...></iframe>  

And when you post the form the iframe will receive the result.

You can do it completely in typescript as described here:

function sendData(data,iframeName,url) {  
  var name;
  var form = document.createElement("form"),
  var node = document.createElement("input");

  form.action = url;
  form.target = iframe.name;

  for(key in data) {
    node.name  = key;
    node.value = data[key].toString();
    form.appendChild(node.cloneNode());
  }

  // To be sent, the form needs to be attached to the //main document.
  form.style.display = "none";
  document.body.appendChild(form);

  form.submit();

  // Once the form is sent, remove it.
  document.body.removeChild(form);
}

And use it with something like

sendData({"a":"val"},"frame1");