Saturday, January 26, 2008

showModalDialog communication with parent window

As pointed out in the MSDN link for showModalDialog Modal Dialog created in IE by showModalDialog() command can send a return val back to calling window. This is a sample code as to how to send lot of information across in such case.

<html>
<head>
<script type="text/javascript">
function fnOpen(){
var sFeatures=fnSetValues();
var returnVal = window.showModalDialog("showModalDialog_target.htm", "",
"dialogHeight: 200px;");
alert(returnVal.amount);
}
</script>
</head>

<body>
Create Modal Dialog Box
<input type="button" value="Push To Create Modal Dialog" onclick="fnOpen()">
</body>
</html>

Then add following code to modal dialog page.

<html>
<head>
<script type="text/javascript">
// a Sample JS object definition (you can include it from external js also)
function PayoffData(){
this.amount=null;
this.vehicle=null;
this.dealType=null;
}
function window.onbeforeunload()
{
var payoffData = new PayoffData();
// sample hardcoding. you can read data from your modal dialog page
payoffData.amount=1200;
payoffData.vehicle='dodge ram';
payoffData.dealType='lease';
window.returnValue = payoffData;
}
</script>
<head>
<body>
<h1>this is ModalDialog.htm<h1>
</body>
</html>
Important things to note:
  • You can now have complete Javascript object sent to and fro between parent and modal dialog.
  • window.onbeforeunload was overridden. that means whether you use a custom close button inside your modal dialog or you use the close button in right top corner of the modal dialog, your data would always be sent back.
  • the parent window script gets blocked when we call window.showModalDialog. We just need to understand that if we have script block after this call, it would be executed only after the modal window closes. (Showing modal window is a synchronous event).
That's all for the day!

No comments: