Implement mediawiki.confirmCloseWindow module
[lhc/web/wiklou.git] / resources / src / mediawiki / mediawiki.confirmCloseWindow.js
1 ( function ( mw, $ ) {
2 /**
3 * @method confirmCloseWindow
4 * @member mw
5 *
6 * Prevent the closing of a window with a confirm message (the onbeforeunload event seems to
7 * work in most browsers.)
8 *
9 * This supersedes any previous onbeforeunload handler. If there was a handler before, it is
10 * restored when you execute the returned function.
11 *
12 * var allowCloseWindow = mw.confirmCloseWindow();
13 * // ... do stuff that can't be interrupted ...
14 * allowCloseWindow();
15 *
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
23 */
24 mw.confirmCloseWindow = function ( options ) {
25 var savedUnloadHandler,
26 mainEventName = 'beforeunload',
27 showEventName = 'pageshow';
28
29 options = $.extend( {
30 message: mw.message( 'mwe-prevent-close' ).text(),
31 test: function () { return true; }
32 }, options );
33
34 if ( options.namespace ) {
35 mainEventName += '.' + options.namespace;
36 showEventName += '.' + options.namespace;
37 }
38
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;
47 }, 1 );
48
49 // show an alert with this message
50 return options.message;
51 }
52 } ).on( showEventName, function () {
53 // Re-add onbeforeunload handler
54 if ( !window.onbeforeunload && savedUnloadHandler ) {
55 window.onbeforeunload = savedUnloadHandler;
56 }
57 } );
58
59 // return the function they can use to stop this
60 return function () {
61 $( window ).off( mainEventName + ' ' + showEventName );
62 };
63 };
64 } )( mediaWiki, jQuery );