window.onbeforeunload in Chrome: what is the most recent fix?
Asked Answered
S

5

30

Obviously, window.onbeforeunload has encountered its fair share of problems with Chrome as I've seen from all the problems I've encountered. What's the most recent work around?

The only thing I've got even close to working is this:

window.onbeforeunload = function () { return "alert" };

However, if I substitute return "alert" with something like alert("blah"), I get nothing from Chrome.

I saw in this question that Google purposefully blocks this. Good for them... but what if I want to make an AJAX call when someone closes the window? In my case, I want to know when someone has left the chatroom on my website, signalled by the window closing.

I want to know if there's a way to either
(a): fix the window.onbeforeunload call so that I can put AJAX in there
or
(b): get some other way of determining that a window has closed in Chrome

Subcelestial answered 8/3, 2012 at 22:27 Comment(1)
See also https://mcmap.net/q/67811/-crossbrowser-onbeforeunloadBlondell
S
15

Answer:

$(window).on('beforeunload', function() {
    var x =logout();
    return x;
});
function logout(){
        jQuery.ajax({
        });
        return 1+3;
}

A little mix and match, but it worked for me. The 1+3 makes sure that the logout function is being called (you'll see 4 if it's successful on the popup when you try to leave).

Subcelestial answered 9/3, 2012 at 3:1 Comment(9)
This does not work in chrome and it will also pop up an alert. Is there a way to ignore the alert in chrome?Fornix
@Subcelestial "4 --- Are you sure you want to leave this page?" is the confirm dialog I get. But the workaround I've found is to return null.Azoth
Hii,This code is not working for me. Do i need to add some jQuery js file or something else ?Gaily
Well, you do need to have jQuery. What's the problem you're getting?Subcelestial
Why not just return 4 instead of 1+3?Victory
@Victory It's just an example.. it doesn't matter at all.Subcelestial
This does not work, it doesn't output the custom message.Hoxie
Does setTimeout() work in the logout method. It's not working for anything more than 1 Sec.Armbruster
For anyone that turns up here, custom message are deprecated by most browsers, reason being that they were abused by some sites, confusing users. So now the message is a generic string which is not controllable by the web page itself. regardless of what string you return. Refer to MDN for more detailed information and specific browser behavioursOuzo
F
11

As of Chrome 117, Chromium has met the standard. The following is tested with Chrome 122.0.6261.129 and Edge 122.0.2365.92.

Test with StackBlitz!

  • The standard states that prompting can be controlled by canceling the event or setting the return value to a non-null value.
  • The standard states that authors should use Event.preventDefault() instead of returnValue.
  • The standard states that the message shown to the user is not customizable.

window.addEventListener('beforeunload', function (e) {
    // Cancel the event as recommended by the standard.
    e.preventDefault();
    // Alternatively, cancel the event by setting `returnValue`.
    e.returnValue = '';
});
    
window.location = 'about:blank';

Prior to 117, Chrome required returnValue to be a non-null value whether set as the return value from the handler or by reference on the event object.

window.addEventListener('beforeunload', function (e) {
    // Chrome requires returnValue to be set.
    e.returnValue = '';
});
    
window.location = 'about:blank';
Faugh answered 16/9, 2018 at 21:27 Comment(3)
@Giulio Caccin the feature was released briefly in 113 but was rolled backed due to breaking a health critical user (issue#1442624). It should be available in 117.Faugh
In recent experience with Chrome: calling event.preventDefault() did not cause the before unload prompt to appear, setting event.returnValue = '' did.Aneroid
@Aneroid Yes, that is what the answer describes for versions prior to 117.Faugh
F
4

Here's a more straightforward approach.

$(window).on('beforeunload', function() {
    return "You should keep this page open.";
});

The returned message can be anything you want, including the empty string if you have nothing to add to the message that Chrome already shows. The result looks like this:

enter image description here

Foretopsail answered 29/6, 2015 at 17:18 Comment(3)
I tried the same thing and it does not work. The alert shows up correctly but without my custom message.Catton
@Catton i think something in the latest chrome update broke this. In my case, the returned custom message was working a week ago but after a chrome patch got installed it no longer does.Situation
@Chronozoa, you are correct: chromestatus.com/feature/5349061406228480Sallie
B
3

According to MDN,

The function should assign a string value to the returnValue property of the Event object and return the same string.

This is the following

window.addEventListener( 'beforeunload', function(ev) { 
    return ev.returnValue = 'My reason';
})
Boondocks answered 21/6, 2016 at 15:12 Comment(4)
This is kind of the right idea, but you forgot to add the 'beforeunload' event to the listener.Giulietta
Thanks very much! This worked on Chrome 63; returning the string without assigning returnValue was not enough.Shane
doesn't seem to entirely work for me on Chrome version " 64.0.3282.186 (Official Build) (64-bit)" or Firefox 58.0.2 (64-bit) - asks for confirm but not with custom message. I tried the example from the page cited directly and got the same results.Mastigophoran
@BeepBop custom messages are prevented for security reasonSpitler
N
3

This solved my problem why it wasn't working in my app:

Note that the user must interact with the page somehow (clicking somewhere) before closing its window, otherwise beforeunload is ignored in order not prevent abuse.

Nightly answered 30/6, 2021 at 18:10 Comment(1)
hi, you probably forgot to paste your answer?Wun

© 2022 - 2024 — McMap. All rights reserved.