Sudarshan Kalebere Sudarshan Kalebere - 2 months ago 4x
Javascript Question

Javascript funtion to ask before leaving window of if status is true

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(){
alert('please save your changes');
return "Do you want to leave?"
return true;


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


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.