Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you fire an event in JavaScript before the user closes the window?

I want to send a ping to my server using an AJAX GET or POST, right after they close the window. Is window.onbeforeunload a good idea?

like image 713
Zack Burt Avatar asked Aug 13 '10 08:08

Zack Burt


2 Answers

Yes, you can send an AJAX request in the window.onbeforeunload but it is not guaranteed that you will get a response before the browser closes so you could only send the request but don't rely on reading a response. If you need to get a response you could send a synchronous request instead of asynchronous.

like image 153
Darin Dimitrov Avatar answered Oct 07 '22 15:10

Darin Dimitrov


Darlin is right, window.onbeforeunload solves the problem not 100%. If it's appropriate - you can show an alert() after sending and ajax request, this will block the browser and your request should be finished, but there's not 100% solution to this problem from my experience :\

like image 27
gothy Avatar answered Oct 07 '22 14:10

gothy