tawheed
tawheed

Reputation: 5821

Submit form after onbeforeunload event in JavaScript

I am trying to submit a form after a onbeforeunload event in JavaScript and it does not seem to entirely work well. Or maybe it could be that I am not doing it well in code.

In my JavaScript, this is the code I have:

function setPopUpWindow(submitForm){
    window.onbeforeunload = function () {
        if (submitForm == false ) {
        return "Unsaved Data would be lost";
        document.getElementById("popUpForm").submit();
        }
        
    }
}

The user sees an alert box after they try and close the browser. After they click on OK in the alert box I am hoping the form would be submitted.

There is a reason why I want to submit the form after they click on close button. I want to get an exit status which I would use for something else in my code (I have an idea of how I am going to implement it).

Upvotes: 1

Views: 4789

Answers (1)

xCander
xCander

Reputation: 1338

You will have to do some ugly stuff in order to achieve what you want:

var saveBeforeUnload = false;
setInterval(function() {
  if (saveBeforeUnload) {
    saveBeforeUnload = false;
    document.getElementById("popUpForm").submit();  
  }
}, 500);

window.onbeforeunload = function() {
  if (submitForm == false) {
    saveBeforeUnload = true;
    return "Don't you want to save before leaving this page?";
  }
};

Upvotes: 4

Related Questions