Ionică Bizău Ionică Bizău - 3 months ago 42
Javascript Question

Is it possible to display a custom message in the beforeunload popup?

When using

window.onbeforeunload
(or
$(window).on("beforeonload")
), is it possible to display a custom message in that popup?

Maybe a small trick that works on major browsers?

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.

So, how to display a custom message in the beforeunload popup? Is that even/still possible?

Answer

In order to set a confirmation message before the user is closing the window you can use

$(window).bind("beforeunload",function(event) {
    return "You have some unsaved changes";
});

Note that

  1. NOT all browsers support this (more info in the Browser compatibility section on MDN)
  2. In Firefox you MUST do some real interaction with the page in order for this message to appear to the user.
  3. Each browser can add his own text to your message.

Here are the results using the browsers I have access to:

Chrome:

Chrome alert on exit

Firefox:

Firefox alert on exit

Safari:

Safar alert on exit

IE:

IE alert on exit

Just to make sure - you need to have jquery included