From 7c123dec4b96e7c3ce5f5a78e828c8aa335bea98 Mon Sep 17 00:00:00 2001 From: Michał Gołębiowski-Owczarek Date: Tue, 18 Feb 2025 20:54:09 +0100 Subject: Event: Use `.preventDefault()` in beforeunload So far, a result of an event handler has been assigned to the `returnValue` of the original event by jQuery. Initially, one could pass a message the browser will then display to the user. Since that got abused a lot, every browser stopped using the provided string and they all now provide a generic message. From the browsers supported in v4, only IE 11 would still display the message. Incidentally, IE 11 is the only browser from our supported ones which respects the value returned from a beforeunload handler attached by `addEventListener`; other browsers do so only for inline handlers, so not setting the value directly shouldn't reduce any functionality. This looks like a good moment to stop passing the message through and just call `event.preventDefault()` without extra checks which is shorter. This used to not work in Chrome but it got implemented in Chrome 119. Unfortunately, it's hard to test this event in unit tests since it blocks page dismissal. Closes gh-5626 --- src/event.js | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/event.js b/src/event.js index a216f9a8c..eafc1480a 100644 --- a/src/event.js +++ b/src/event.js @@ -485,12 +485,17 @@ jQuery.event = { beforeunload: { postDispatch: function( event ) { - - // Support: Chrome <=73+ - // Chrome doesn't alert on `event.preventDefault()` - // as the standard mandates. - if ( event.result !== undefined && event.originalEvent ) { - event.originalEvent.returnValue = event.result; + if ( event.result !== undefined ) { + + // Setting `event.originalEvent.returnValue` in modern + // browsers does the same as just calling `preventDefault()`, + // the browsers ignore the value anyway. + // Incidentally, IE 11 is the only browser from our supported + // ones which respects the value returned from a `beforeunload` + // handler attached by `addEventListener`; other browsers do + // so only for inline handlers, so not setting the value + // directly shouldn't reduce any functionality. + event.preventDefault(); } } } -- cgit v1.2.3