The most popular question for this has many answers, but sadly I can't find one that works properly. Most responses are from 10 years ago, some don't even work:
There are also many variations of the same bit of code (for example, some add "e.returnValue='';" to the code, while many others don't.
What is the best way to do this detection? Is it beforeunload still? How would the code look like in 2021 to cover modern browsers/behaviors?
(To avoid an XY problem, I want to show a confirmation popup if the user tries to close the page. The popup is easy, the detection is not.)
This is a duplicate. Answers on the other question specify onunload
and beforeunload
events, both of which have very good browser compatibility (onunload and beforeunload).
I tried this solution (randomly picked) in my browser console and it just worked out of the box:
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "tab close";
(e || window.event).returnValue = confirmationMessage; //Gecko + IE
sendkeylog(confirmationMessage);
return confirmationMessage; //Webkit, Safari, Chrome etc.
});
Also, 3~4 of the answers to that question are after 2018! How can they be old?!
I'll eventually edit the answer to include details on how that specific page does it.
Edit: I checked the page, the only check that was made was this:
$(window).unbind().bind('beforeunload', function(){
return 'You are about to disconnect from this chat, are you sure you want to leave?';
});
This code is verbatim, and is bad. As mentioned by @charlietfl, bind()
and unbind()
are deprecated methods. From the documentation:
As of jQuery 3.0, .bind() has been deprecated. It was superseded by the .on() method for attaching event handlers to a document since jQuery 1.7, so its use was already discouraged.
So please use on()
instead.