0

I have a web page that calls a post request just before the user tries to exit the page. I am using the window.onbeforeunload event to achieve that. It works when I leave the page a few seconds after I enter the page, but it doesn't when I stay idle for a few minutes. Here's my Javascript:

window.onbeforeunload = function() {
  $.post('http://52.91.227.233:1000/set_day',
    {username: user, useday: day}
  );
};

According to my observation, there's no problem with the post request or the NodeJS app. It is a problem in the onbeforeunload event, though I don't know what exactly the problem is. I've also tried beforeunload but it still doesn't work

Thanks!

Max Stoll
  • 1
  • 1
  • See this answer: https://stackoverflow.com/a/42914045/2137269 - onbeforeunload is not guaranteed to execute. – Evan Knowles Apr 14 '22 at 06:56
  • Read the answer... But still doesn't help because the problem is it works only if the user tries to leave just a few minutes after the entry into the page. – Max Stoll Apr 14 '22 at 07:05
  • But if you still think it helps, then may I know in which way? – Max Stoll Apr 14 '22 at 07:06
  • Also, keep in mind if you try to make it synchronous you have other problems https://stackoverflow.com/questions/15479103/can-beforeunload-unload-be-used-to-send-xmlhttprequests-reliably, and send beacon is not recommended either. You should solve this issue in your server instead. For example, you can create a heartbeat pattern to detect if someone left the page in addition to these tricks you cannot trust, – Abdurrahim Apr 14 '22 at 07:09

0 Answers0