|
1 | | -( function ( $ ) { |
2 | | - var $form, |
3 | | - originalFormContent, |
4 | | - isSubmitting = false, |
5 | | - hasListener = false, |
6 | | - __ = wp.i18n.__; |
| 1 | +/* global wp */ |
| 2 | +( function () { |
| 3 | + var form = document.querySelector( 'form[action="options.php"]' ); |
7 | 4 |
|
8 | | - function beforeUnloadHandler() { |
9 | | - if ( isSubmitting || ! $form || ! $form.length ) { |
10 | | - return; |
11 | | - } |
| 5 | + if ( ! form ) { |
| 6 | + return; |
| 7 | + } |
12 | 8 |
|
13 | | - if ( originalFormContent !== $form.serialize() ) { |
| 9 | + var originalFormContent = new URLSearchParams( new FormData( form ) ).toString(); |
| 10 | + var __ = wp.i18n.__; |
| 11 | + |
| 12 | + function beforeUnloadHandler( event ) { |
| 13 | + var currentContent = new URLSearchParams( new FormData( form ) ).toString(); |
| 14 | + if ( originalFormContent !== currentContent ) { |
| 15 | + event.preventDefault(); |
14 | 16 | return __( |
15 | 17 | 'The changes you made will be lost if you navigate away from this page.' |
16 | 18 | ); |
17 | 19 | } |
18 | 20 | } |
19 | 21 |
|
20 | | - function addBeforeUnloadListener() { |
21 | | - if ( ! hasListener ) { |
22 | | - $( window ).on( 'beforeunload.options', beforeUnloadHandler ); |
23 | | - hasListener = true; |
24 | | - } |
25 | | - } |
26 | | - |
27 | | - function removeBeforeUnloadListener() { |
28 | | - if ( hasListener ) { |
29 | | - $( window ).off( 'beforeunload.options' ); |
30 | | - hasListener = false; |
31 | | - } |
32 | | - } |
33 | | - |
34 | | - $( function () { |
35 | | - $form = $( 'form[action="options.php"]' ); |
36 | | - |
37 | | - if ( ! $form.length ) { |
38 | | - return; |
39 | | - } |
40 | | - |
41 | | - originalFormContent = $form.serialize(); |
42 | | - |
43 | | - // Add listener only when form is modified |
44 | | - $form.on( 'change input', function () { |
45 | | - addBeforeUnloadListener(); |
46 | | - } ); |
| 22 | + // Add the beforeunload listener only once a field is modified, to avoid |
| 23 | + // breaking bfcache. |
| 24 | + document.addEventListener( 'change', function () { |
| 25 | + window.addEventListener( 'beforeunload', beforeUnloadHandler ); |
| 26 | + }, { once: true } ); |
47 | 27 |
|
48 | | - $form.on( 'submit', function () { |
49 | | - isSubmitting = true; |
50 | | - removeBeforeUnloadListener(); |
51 | | - } ); |
| 28 | + form.addEventListener( 'submit', function () { |
| 29 | + window.removeEventListener( 'beforeunload', beforeUnloadHandler ); |
52 | 30 | } ); |
53 | | -} )( jQuery ); |
| 31 | +} )(); |
0 commit comments