5

I want to hook into certain events on a SharePoint 2010 site, specifically the modal dialog open and close events.

Does SharePoint 2010 trigger any events for these kinds of actions? If so, how do I register an event listener?

Working with out of the box installation of SharePoint and only have access to client side code.

2 Answers 2

8
+50

To intercept all modals if you don't have control on their triggers, you might want to do a "catch all" proxy pattern:

SP.UI.ModalDialog.showModalDialog_old = SP.UI.ModalDialog.showModalDialog;
SP.UI.ModalDialog.showModalDialog = function(options) { 
   console.log(0); //do stuff
   SP.UI.ModalDialog.showModalDialog_old(options);
};

You will want to do that after sp.ui.js loads, there are some ways of doing that but if you have jQuery a simply $(function() { }); will do.

Now to capture the close event it isn't as simple since the same pattern above doesn't seem to work on the SP.UI.ModalDialog.commonModalDialogClose but you can simply attach to it with a jQuery selector:

$("a[id^=DlgClose]").click(function() { 
  // modal X button clicked. 
});
2
  • 1
    +1 But I think you missed the bit where you set SP.UI.ModalDialog.showModalDialog_old
    – Stu Pegg
    Commented Jan 29, 2013 at 9:35
  • I get Uncaught TypeError: Cannot read property 'getElementsByTagName' of undefined(…) Commented Mar 22, 2016 at 23:24
4

I don't know if this is what you are after, but I post anyhow.

If you make a custom call to the modal dialog, you can execute your own code before you show the dialog.

//Dialog Opening
function OpenDialog() {
    var options = SP.UI.$create_DialogOptions();
    options.url = '/Pages/myPage.aspx';
    options.dialogReturnValueCallback = Function.createDelegate(null, CloseCallback);
    SP.UI.ModalDialog.showModalDialog(options);
}

The callback function can be like this:

function CloseCallback(result, target) {
    if (result == SP.UI.DialogResult.OK) {
        // Your OK code
    }
    if (result == SP.UI.DialogResult.cancel) {
        // Your cancel code
    }
}
1
  • Thanks, but I won't be making custom calls, I need to hook onto every modal open and close whether custom or built in.
    – Fergal
    Commented Jan 29, 2013 at 11:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.