locked
Sending message from iFrame to Main window

    Question

  • I have created a iFrame to load webpage, which is in web context. I want to send message from this web context to local context. IS there a way to send message? I can send message from local to web but need vice versa. any pointers would be appreciated

    David

    Tuesday, November 01, 2011 9:54 PM

Answers

  • Yes, you can use the HTML5 postMessage API to send messages both directions. To send web to local, the trick is that you need to invoke postMessage on the target element. Since you can't address elements in the local page by id, you need to use window.parent as the target. This will send a message to the local element that contains the iframe.

    To be specific, your iframe would have code like this:

    window.parent.postMessage(message, "*");

    The parent element of that iframe would pick the message up as follows,

    element.addEventListener("message", function () { ... });
    

     

    .Kraig

     

     

    Tuesday, November 01, 2011 10:42 PM
  • Tuesday, November 01, 2011 11:50 PM

All replies

  • Yes, you can use the HTML5 postMessage API to send messages both directions. To send web to local, the trick is that you need to invoke postMessage on the target element. Since you can't address elements in the local page by id, you need to use window.parent as the target. This will send a message to the local element that contains the iframe.

    To be specific, your iframe would have code like this:

    window.parent.postMessage(message, "*");

    The parent element of that iframe would pick the message up as follows,

    element.addEventListener("message", function () { ... });
    

     

    .Kraig

     

     

    Tuesday, November 01, 2011 10:42 PM
  • Tuesday, November 01, 2011 11:50 PM
  • Thanks Kriag/jrboddie.
    Wednesday, November 02, 2011 4:53 PM