Sunday, September 2, 2012

How to show Confirm Navigation using onbeforeunload event in javascript

I think, you have an experience as if you see "Confirm Navigation" popup when you close Browser. Let's say, when you clicks other link or close browser in Facebook before pressing "Post" button during post something, you will get the following confirm dialog.
Confirm Navigation in FB
This example sohow you how to use the onbeforeunload event to ask users whether they want to remain on the current document or refresh the page again. When the user press F5 or attempts to close the window, the onbeforeunload event fires on the body and a dialog box displays. If the user chooses OK, the document refresh again or closes the window; if the user chooses Cancel, the document remains the same.
Copy the following script to <head> tag.
<script type="text/javascript">
document.onkeydown = getKeyCode;
var keyCode = 0;
window.onbeforeunload = confirmExit;
function confirmExit() {
    // F5 is 116.
    if (keyCode == 116) 
        keyCode = 0;
        // For F5
        return "If you have made any changes to the fields without clicking the Save button, " +
        "Your changes will be lost. Are you sure you want to exit this page?";
        // For close browser
        return "You have attempted to leave this page." +
        "Are you sure you want to exit this page?";
function getKeyCode(e) {
    if (window.event) {
        e = window.event;
        keyCode = e.keyCode;
    else {
        keyCode = e.which;
That's it. When you close the browser or press F5, it show the "Confirm Navigation" popup with the different message. Now, it don't work in IE 7. If you know the root cause, please drop a line. Thank!

1 comment:

  1. Thank you so much! This is exactly what I was looking for! I looked all over the internet and I could not find what I was looking for! Now I got a code for mu chatroom! Thanks a ton!