Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using postmessage to refresh iframe's parent document

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

like image 564
aperture Avatar asked Sep 26 '10 23:09

aperture


People also ask

What is window postMessage () used for?

postMessage() The window. postMessage() method safely enables cross-origin communication between Window objects; e.g., between a page and a pop-up that it spawned, or between a page and an iframe embedded within it.

Does postMessage work cross domain?

PostMessage() is a global method that safely enables cross-origin communication. It's a lot like Ajax but with cross-domain capability. We'll give it a whirl by setting up two-way communication between a web page and an iframe whose content resides on another server.

What does postMessage return?

postMessage() sends a message back to the main page. The two ends can listen to messages from the other using window. addEventListener("message", (event) => {...}) .

Is postMessage synchronous?

The postMessage() function is asynchronous, meaning it will return immediately. So you can not do synchronous communication with it. In your example, the posted message will vanish in the void, because there is no listener for the message event at the time the postMessage() function is executed.


1 Answers

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).

like image 197
Scott Wilson Avatar answered Sep 20 '22 08:09

Scott Wilson