When using window.onbeforeunload
(or $(window).on("beforeonload")
), is it possible to display a custom message in that popup?
Not anymore. All major browsers have started ignoring the actual message and just showing their own.
By looking at existing answers I have the feeling this was possible in the past using things like confirm
or alert
or event.returnValue
, but now it seems they are not working anymore.
Correct. A long time ago, you could use confirm
or alert
, more recently you could return a string from an onbeforeunload
handler and that string would be displayed. Now, the content of the string is ignored and it's treated as a flag.
When using jQuery's on
, you do indeed have to use returnValue
on the original event:
$(window).on("beforeunload", function(e) {
// Your message won't get displayed by modern browsers; the browser's built-in
// one will be instead. But for older browsers, best to include an actual
// message instead of just "x" or similar.
return e.originalEvent.returnValue = "Your message here";
});
or the old-fasioned way:
window.onbeforeunload = function() {
return "Your message here"; // Probably won't be shown, see note above
};
That's all you can do.