How to handle ajax and close pages

If the user experiences a delay in connecting to my site, ajax does not expire, and the user decides to close the window. Will the ajax request be terminated? Is there a way in which I can say that you are still working, do you want to leave this page? (bonus if it is closed as soon as ajax is successful). How to do it?

I'm not sure if this is the same (maybe it is built into firefox?), But when I closed this page, he said

Are you sure you want to go from this page?

You started writing or editing a message.

Click OK to continue, or Cancel to stay on the current page.

I am sure I saw this in other places. How to do this if the user is not sending ajax and is in the middle of the message?

+4
source share
2 answers

You can use the window.onbeforeunload event for this. Set the variable to false at the beginning of the ajax request. And in the callback function, set its value to true, and in the window.onbeforeunload event, check this variable and display the corresponding message.

Note

This will work when the page is refreshed.

+4
source

You can implement the onbeforeunload handler in js:

 window.onbeforeunload = function() { if (showMessage) { return trye } else { return; } } 
+1
source

Source: https://habr.com/ru/post/1301090/


All Articles