0

I have a activestatus var which tells whether saving to file are done or not, if file is not saved activestatus will be true in that case if user presses browser back or tries to type different url and go he should get a pop up saying "You have not saved changes you want to save? yes no".

here is what I tried so far

var activeInput=true;
 window.onbeforeunload =checkNow;

    function checkNow(){
        if(activeInput==true){
            alert('please save your changes');
            return "Do you want to leave?"
        }else{
            alert('gonow');
            return true;
        }

    } 

Basically I want to call a function only when user wants to leave the window and saving to file is not done.

Sudarshan Kalebere
  • 3,813
  • 3
  • 34
  • 64

1 Answers1

2

Try using addEventListener, and use e.returnValue to show the message.

var activeInput=true;

window.addEventListener('beforeunload', checkNow);

function checkNow(e) {
        if (activeInput === false) return true;
        var message = "Are you sure you want to leave this page? Ensure you save any changes.";
        e.returnValue = message;
        return message;
}

Here is a jsFiddle. You can read more about the onbeforeunload event, including the behavior of e.returnValue here.

Sinan Guclu
  • 1,075
  • 6
  • 16