Skip to content

Commit 7c123de

Browse files
authored
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 jquerygh-5626
1 parent 047f868 commit 7c123de

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

src/event.js

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -485,12 +485,17 @@ jQuery.event = {
485485

486486
beforeunload: {
487487
postDispatch: function( event ) {
488-
489-
// Support: Chrome <=73+
490-
// Chrome doesn't alert on `event.preventDefault()`
491-
// as the standard mandates.
492-
if ( event.result !== undefined && event.originalEvent ) {
493-
event.originalEvent.returnValue = event.result;
488+
if ( event.result !== undefined ) {
489+
490+
// Setting `event.originalEvent.returnValue` in modern
491+
// browsers does the same as just calling `preventDefault()`,
492+
// the browsers ignore the value anyway.
493+
// Incidentally, IE 11 is the only browser from our supported
494+
// ones which respects the value returned from a `beforeunload`
495+
// handler attached by `addEventListener`; other browsers do
496+
// so only for inline handlers, so not setting the value
497+
// directly shouldn't reduce any functionality.
498+
event.preventDefault();
494499
}
495500
}
496501
}

0 commit comments

Comments
 (0)