summaryrefslogtreecommitdiff
path: root/extensions/Vector/modules/ext.vector.editWarning.js
blob: e6ee5c601c04c602af9ef4cca075a2ea688e81a5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
 * Edit warning for Vector
 */
( function ( mw, $ ) {
	$(document).ready( function () {
		// Check if EditWarning is enabled and if we need it
		if ( $( '#wpTextbox1' ).length === 0 ) {
			return true;
		}
		// Get the original values of some form elements
		$( '#wpTextbox1, #wpSummary' ).each( function () {
			$(this).data( 'origtext', $(this).val() );
		});
		// Attach our own handler for onbeforeunload which respects the current one
		var otherOnBeforeUnload = window.onbeforeunload;
		function ourOnBeforeUnload() {
			var fallbackResult, retval;

			// Check if someone already set an onbeforeunload hook
			if ( otherOnBeforeUnload ) {
				// Get the result of their onbeforeunload hook
				fallbackResult = otherOnBeforeUnload();
			}

			// Check if their onbeforeunload hook returned something
			if ( fallbackResult !== undefined ) {
				// Exit here, returning their message
				retval = fallbackResult;
			} else {
				// Check if the current values of some form elements are the same as
				// the original values
				if (
					mw.config.get( 'wgAction' ) == 'submit' ||
						$( '#wpTextbox1' ).data( 'origtext' ) != $( '#wpTextbox1' ).val() ||
						$( '#wpSummary' ).data( 'origtext' ) != $( '#wpSummary' ).val()
				) {
					// Return our message
					retval = mw.msg( 'vector-editwarning-warning' );
				}
			}

			// Unset the onbeforeunload handler so we don't break page caching in Firefox
			window.onbeforeunload = null;
			if ( retval !== undefined ) {
				// ...but if the user chooses not to leave the page, we need to rebind it
				setTimeout( function () {
					window.onbeforeunload = ourOnBeforeUnload;
				}, 1 );
				return retval;
			}
		}

		// Do the first binding now
		window.onbeforeunload = ourOnBeforeUnload;

		function pageShowHandler() {
			// Re-add onbeforeunload handler on pageshow.
			window.onbeforeunload = ourOnBeforeUnload;
		}

		$( window ).on( 'pageshow', pageShowHandler );

		// Add form submission handler
		$( '#editform' ).submit( function () {
			// Restore whatever previous onbeforeload hook existed
			window.onbeforeunload = otherOnBeforeUnload;
		});
	});

}( mediaWiki, jQuery ) );