Hammad
Hammad

Reputation: 2137

Call beforeunload only when user is closing the browser/tab

I have used beforeunload event on my page so that when user tries to close my website/tab then I prompt the user that they should not leave the site unless all the forms are filled. But the problem is that my page has a rich form which reloads after every section form fill.

Means page has several forms and each has its own submit button. When user saves one form the page should reload. But at reload beforeunload gets fired and asks user "Do you want to leave the website?". The user did not intend to leave the website, they just reloaded the page.

In short I want to avoid beforeunload on page reload and only call it when user tries to close the tab or browser. Is that possible.

I tried the following code but that did not work:

window.onbeforeunload = function(e) {
  var e = e || window.event;
  var target = e.target.URL;

  if (target == "http://mywebsite.com/customerdetails")
  {
    return false;
  }
};

Upvotes: 2

Views: 4831

Answers (3)

Adrian Brand
Adrian Brand

Reputation: 21638

Set a variable when the click one of the navigation buttons like var navigating = true; and in the onbeforeunload event handler check if it is navigating.

Upvotes: 0

Mosh Feu
Mosh Feu

Reputation: 29277

It seems that in both of the cases (submit and close the window) the target is the same.

Keep a "flag" like formSubmitted and set it to false. Once you submit the form set it to true. In the onbeforeunload check if the formSubmitted is false or true.

Something like this:

var formSubmitted = false;

window.onbeforeunload = function(e) {
  var e = e || window.event;
  var target = e.target.URL;

  if (!formSubmitted)
  {
    return false;
  }
};
<form action="/asdf" onsubmit="formSubmitted = true">
  <input type="text" name="test" />
  <button>Submit</button>
</form>

http://output.jsbin.com/hayahut

Upvotes: 2

Arun Ghosh
Arun Ghosh

Reputation: 7734

I once had same issue and couldn't get a good solution. The workaround I found was that to unsubscribe onbeforeunload before you reload the page. And then attach it once the page is reloaded.

Upvotes: 1

Related Questions