0

I´m trying for a while execute a JavaScript function when a user leaves web site by typing a address in the browser and hits return or the user closes the browser clicking in the x button.

I tried the unload event but I cannot get the alert.

This is what I am doing:

$(window).unload(function () {
    alert("Are you sure?");
});

also

$(body).unload(function () {
    alert("Are you sure?");
});

I am running out of ideas!

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Guilherme Longo
  • 2,278
  • 7
  • 44
  • 64

4 Answers4

2

You can listen to beforeunload event that fires before the unload event, when the page is unloaded.

$(window).on('beforeunload', function(){
    // ...
})
Ram
  • 143,282
  • 16
  • 168
  • 197
  • 1
    beforeunload expects you to return a string, I believe, which is probably worth pointing out. – Phil H Nov 30 '12 at 14:49
2

Some browsers (like Chrome) block alerts in unload event handlers, to prevent exactly these kind of annoying messages. Try a console.log or put a breakpoint in to find out if the handler is triggered when you don't have an alert there.

SO question on a similar line:

window.onunload is not working properly in Chrome browser. Can any one help me?

You can only pass the alert by returning a string in a beforeunload handler (HT @undefined), but I would avoid even that, because popups are generally bad, and most people will do minimum processing to work out the make-this-thing-go-away option before they actually think about the contents of the box.

Community
  • 1
  • 1
Phil H
  • 19,928
  • 7
  • 68
  • 105
1

The function you defined in window.onbeforeunload if it returns a string it will pop up a confirm navigation prompt with that message.

Alerts may be ignored!

window.onbeforeunload = function() {
    return "All unsaved data will be lost. Are you sure?";
};

Some browsers handle the onbeforeunload differently. Recent Firefox for example will ignore your return string and just display a standard message.

Jazaret
  • 3,655
  • 3
  • 17
  • 15
0
$(window).bind('beforeunload', function(){
    alert("Are your sure?")
});
Paul M
  • 366
  • 1
  • 3
  • 8