Is it possible to send AJAX after closing the browser window?

Is it possible to send AJAX after closing the browser window?

I have a browser game with movement in JavaScript (jQuery), and if I send Ajax after each movement, it will be difficult for the server. So I want to send one AJAX when the user closes the window (or bookmark). It should be functional in all modern browsers.

thanks for answers

+6
source share
5 answers

I suggest you update the server on some kind of timer so that the server never goes too far, knowing what state the client is in (possibly every 60 seconds when the client is active), pausing server updates when the client is not active.

Then, in your user interface, put some obvious user interface elements for Close or Stop that prompt the user to disable this path, and then update the server when you hit any of these buttons.

Then you can also hook up the unload event for the page and send one last ajax call. But this is not called in every case or is supported in all browsers, so this will be done in addition to the two previous methods.

+5
source

I don’t think there is a practical way to do this ... but there is definitely a solution to your problem.

You can send your request either after a certain period of time, or when the game arrives at a certain stage.

We do not see the full scenario, so please rate a little more so that I or someone else can help.

If possible, I would add “Save state” or just “Save”. Therefore, the user knows that if he did not hit Save, nothing will be Saved.

+1
source

You can try window.onbeforeunload for example:

 function saveGame(e) { if (!e) e = window.event; //Ajax here } window.onbeforeunload = saveGame; 
+1
source

I can suggest the following:

  • invoke window.onunload (pay attention to firefox!) and save the current location on the server. important: make this asynchronous call.
  • save the user state on the server (leaving the page)
  • write the code in the global request event handler and request this state.
  • you can start threads on the server to cause the final unload (say, after 5 seconds) of any new request from the client

I know that these steps are difficult to implement, but they solve your problem and solve it.

0
source

You cannot send any ajax request after closing the browser window. But you can use the onUnload event to send an ajax request when the user clicks the close window button.

0
source

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


All Articles