Search code examples
htmlonbeforeunload

window.onbeforeunload runs only when closing window not on refresh


I have this function

 window.onbeforeunload = function () {        
          return "Are you sure?";        
    };

and I have a button that when the user presses it the window refreshes to update screen values and do some database calls. I added window.onbeforeunload=null; in the beginning of the function to disable onbeforeunload but it kept being called.

Is there a way to either disable the onbeforeunload function in my button onclick function or make the window.onbeforeunload get called only on close window not on refresh?


Solution

  • Following code should work (should be kept inside head tag between script tags)

    window.onload=function(){
    
        window.onbeforeunload = function(){        
            return "Are you sure?";        
        }
    
        document.getElementById('refresh').onclick=function(){
            window.onbeforeunload = null;
            window.location.reload(); // replace with your code
        }
    }​
    

    WORKING DEMO.