using postmessage to refresh iframe's parent document

aperture picture aperture · Sep 27, 2010 · Viewed 29.1k times · Source

I have a greasemonkey script that opens an iframe containing a form from a different sub-domain as the parent page.

I would like to refresh the parent page when the iframe refreshes after the form submission

I am at the point where I can execute a function when the iframe refreshes, but I cannot get that function to affect the parent document.

I understand this is due to browser security models, and I have been reading up on using postMessage to communicate between the two windows, but I cannot seem to figure out how to send a reload call to the parent with it.

Any advice on how to do that would be very helpful

thanks

Answer

Scott Wilson picture Scott Wilson · Jan 14, 2011

Use:

window.parent.postMessage('Hello Parent Frame!', '*');

Note the '*' indicates "any origin". You should replace this with the target origin if possible.

In your parent frame you need:

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

function receiveMessage(evt)
{
  if (evt.origin === 'http://my.iframe.org')
  {
    alert("got message: "+evt.data);
  }
}

Replace "my.iframe.org" with the origin of your iFrame. (You can skip the origin verification, just be very careful what you do with the data you get).