3 * @method confirmCloseWindow
6 * Prevent the closing of a window with a confirm message (the onbeforeunload event seems to
7 * work in most browsers.)
9 * This supersedes any previous onbeforeunload handler. If there was a handler before, it is
10 * restored when you execute the returned function.
12 * var allowCloseWindow = mw.confirmCloseWindow();
13 * // ... do stuff that can't be interrupted ...
16 * @param {Object} [options]
17 * @param {string} [options.namespace] Namespace for the event registration
18 * @param {string} [options.message]
19 * @param {string} options.message.return The string message to show in the confirm dialog.
20 * @param {Function} [options.test]
21 * @param {boolean} [options.test.return=true] Whether to show the dialog to the user.
22 * @return {Function} Execute this when you want to allow the user to close the window
24 mw.confirmCloseWindow = function ( options ) {
25 var savedUnloadHandler,
26 mainEventName = 'beforeunload',
27 showEventName = 'pageshow';
30 message: mw.message( 'mwe-prevent-close' ).text(),
31 test: function () { return true; }
34 if ( options.namespace ) {
35 mainEventName += '.' + options.namespace;
36 showEventName += '.' + options.namespace;
39 $( window ).on( mainEventName, function () {
40 if ( options.test() ) {
41 // remove the handler while the alert is showing - otherwise breaks caching in Firefox (3?).
42 // but if they continue working on this page, immediately re-register this handler
43 savedUnloadHandler = window.onbeforeunload;
44 window.onbeforeunload = null;
45 setTimeout( function () {
46 window.onbeforeunload = savedUnloadHandler;
49 // show an alert with this message
50 if ( $.isFunction( options.message ) ) {
51 return options.message();
53 return options.message;
56 } ).on( showEventName, function () {
57 // Re-add onbeforeunload handler
58 if ( !window.onbeforeunload && savedUnloadHandler ) {
59 window.onbeforeunload = savedUnloadHandler;
63 // return the function they can use to stop this
65 $( window ).off( mainEventName + ' ' + showEventName );
68 } )( mediaWiki, jQuery );