Window.onbeforeunload problem

is there a way to detect if the user navigates away from the page, this includes all ways of navigating such as typing the address, back button click etc…?

I have searched and found out the window.onbeforeunload function. This might be helpful if I just want to check if the user wants to continue navigating or not. What I actually wanted was something like this:

There is a form where the user can edit his/her details. If there is a change and the user does not saved it and accidentally clicks another link, the program will ask if the user will “save”, “discard”, or “cancel” these changes. As for the onbeforeunload, it would be the “discard” and “cancel” only. So for my question, Is there a way solve this problem?

The onbeforeonload event triggers on all occasions when the current page is unloaded. This includes going back to the previous page, closing the window, and clicking on a link on your page. Every time the page changes to another page, whether it is within your website r not, that triggers the event.

You can not determine which type of behaviour has occurred when the event is triggered.

That is actually what I’m trying to solve. Either if there is a workaround similar to this one or is there a way I can call a function instead of this dialog box?

From within the fuction you attach to the onbeforeunload event, you can run whatever code you wish to run, and then return false from the event to prevent the window from unloading.


window.onbeforeunload = function () {
    // do my own thing here
    return false;
};

i tried to do your suggestion but i never get rid of the prompt box…

Ahh that’s right. This one event works different from all of the others.

With onbefore unload, anything that is returned from it is displayed in that confirmation box.
To get rid of it, remove the return statement so that the onbeforeunload function returns nothing at all.

Here’s a page that demos different types of techniques relating to this:

btw, thanks for entertaining all my questions. Honestly, I’ve been following that site already to create the onbeforeunload event screen. I was trying to connect it with this another style

http: / / blogs . dovetailsoftware . com/blogs/gsherman/archive/2007/09/26/using-modern-javascript-libraries-to-create-a-better-user-experience-in-fcclient . aspx
(Sorry I need to do this to post the link…)

I was trying to catch the event, display this new prompt box instead of the default one and do the actions behind this.