2

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; } }; 

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

8 Comments

Thanks for the answer, but not working :( tried your demo as well
What do you mean? In the demo, try to reload, you will see the prompt message. Try to submit the form and you will not. Am I missing something?
I just opened your JSBin link and hit the f5 and it shows alert. I don't want that. I want only when I try to close the tab/window then prompt should show at that time only
I afraid you can't do this. See this answer. The thing you can do, is to check if the mouse leaves the screen only then, show the prompt message. So id the user will click on F5 he will not see it. But if he will refresh using the refresh button on the browser he will see it.
Hmmm...thanks for your help. I upvoted, still looking for better solution
|
1

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.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.