开发者

Is there any possibility how to send an AJAX after close the browser window? [duplicate]

This question already has answers here: JavaScript, browsers, window close - send an AJAX request or run a script on window closing (9 answers) Closed 6 years ago.

Is there any possibility how to send AJAX after close the browser window?

I have a browser game with movement in JavaScript (jQuery) and if I send Ajax after each movement it would be difficult for开发者_Python百科 the server. So I want to send one AJAX when user close the window (or bookmark). It must be functional in all modern browsers.

Thank you for answers


I'd suggest you update the server on some sort of timer so the server never gets too far behind in knowing what state the client is in (perhaps 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 encourages the user to shut-down that way and then update the server when either of those buttons are hit.

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


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

You can send your request either at some time interval or when the game arrives at a particular stage.

We're not seeing the complete scenario so please evaluate a bit more so I or someone else can help.

If possible.. I would add a "Save State" or just "Save" button. So the user knows that if he doesn't hit "Save" nothing will be "Saved".


You can try window.onbeforeunload e.g.:

function saveGame(e) {
     if (!e) e = window.event;

    //Ajax here
}
window.onbeforeunload = saveGame;


You can't send any ajax request after closing browser window. But you can use onUnload event for send ajax request when user click close button of the window.


I can suggest this:

  1. invoke window.onunload (pay attention to firefox!) and store the current location in the server. important: make this async call.
  2. in the server save the state of the user (leaving a page)
  3. write a code in the global request event handler and query this state.
  4. you can launch threads in the server to invoke the final unload (say, after 5 sec) no new request from the client

I know these steps are hard to implement, but they address your problem and solves it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜