Open a page in a SharePoint modal window

Ever have a need to open a page or external URL from your SharePoint site within a modal window? With the dialog framework provided by SharePoint, it is pretty easy to do so.

Here is an example. Add the following JavaScript to your page or a separate JavaScript file (and reference it from your page).

function OpenInModal(url) {
var options = {
url: url,
title: "Client Portal Site Request",
allowMaximize: false,
width: 1100,
height: 700,
dialogReturnValueCallback: refreshCallback
};

SP.UI.ModalDialog.showModalDialog(options);
};

function refreshCallback(dialogResult, returnValue) {
if (dialogResult = SP.UI.DialogResult.OK) {
SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK);
}
};

The ShowRequestForm function accepts the URL which you want to open. There a few options that are set (see MSDN for details), including the width and height of the modal window. The dialogReturnValueCallback: refreshCallback tells it to call the refreshCallback function when the modal window is closed by the user. This is useful if you want to refresh the parent page or show a message to the user when the modal window is closed.

To call the OpenInModal function from your page, you can simply call the JavaScript function from a link or button.

<a href="javascript: ShowRequestForm('<<urltoopen>>');">Open Modal</a>

How to close the modal window programmatically

If you need to close the modal window programmatically you can do so with a couple of lines of code.

context.Response.Write("window.frameElement.commitPopup();");
context.Response.Flush();
context.Response.End();