0

Inside my iframe page, user can add or delete items from a list by ajax calls.

I need to also update the number of items in the list in my parent page. How can I do this?

xpluni
  • 25
  • 1
  • 4

1 Answers1

1

I have done communication between a parent and an iFrame using Javascript in the iFrame to post the message to the parent.

In the iFrame:

window.top.postMessage('Message', '*');

You can also post this message server side (C#) by calling (*Note that you will need a asp:ScriptManager control on the page to do this)

ScriptManager.RegisterStartupScript(this, this.GetType(), "login_message", "javascript:window.top.postMessage('Message', '*');", true);

In the Parent, you will need to setup a listener:

/* Retrieve message from iFrame */
window.onmessage = function (e) {
    var strMessage = e.data.toString();
    if (strMessage == 'Message') {
        /* Message Actions */
    }
};

If you have compatibility issues with IE 7 or 10+, you may need to handle it this way. I found that the way I was doing it above had issues in certain versions of IE (even certain newer ones, like 10).

// Create IE + others compatible event handler
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

// Listen to message from child window
eventer(messageEvent, function (e) {
    var strMessage = e.data.toString();
    if (strMessage == 'Message') {
        /* Message Actions */
    }
}, false);

In this example, the string "Message" is being passed from the iFrame to the parent. The parent stores it in the var strMessage upon receiving it. I then check that the message is what I expect before applying actions. You could easily make the message the number of items in your list.

This is very similar to How to communicate between iframe and the parent site? Note that this will not work in IE 7 or older.

Community
  • 1
  • 1
Jem
  • 3,473
  • 2
  • 16
  • 20