How to make a cross-browser on-window-unload request?

白昼怎懂夜的黑 提交于 2019-12-28 16:14:34

问题


I have a Flash game that I'm trying to save the state of when the user closes the browser tab. It is using the following jquery code:

//Called from Flash when window closes
function sendRequest(url, params) {
    $.ajax({
      type: "POST",
      async: false,
      url: url,
      data: params
    })
}

$(window).unload(function() {
  //Make Flash attempt to save the game when the window closes.
  //Flash gets the necessary data and calls sendRequest()
  document["flashGame"].saveBeforeUnload();
});
  • Firefox: Works correctly
  • Chrome: Works correctly when reloading but not when closing tabs or closing the browser
  • IE (all versions): Does not work at all

I want it to work in all browsers correctly, but most important is Chrome (not many of our users have IE).

Flash is correctly calling sendRequest (in all browsers, tested with an alert), so I don't believe the problems come from Flash, but it might.


回答1:


The short answer is that you can't.

The onbeforeunload event was initially introduced by Microsoft to allow a standard confirmation dialog. It is now supported in the original form by most browsers and in most case a short, non interactive, function is allowed to execute (for example you may log your state in the localStorage). But, as described in the cross-browser jQuery API, this is unreliable :

The exact handling of the unload event has varied from version to version of browsers. For example, some versions of Firefox trigger the event when a link is followed, but not when the window is closed. In practical usage, behavior should be tested on all supported browsers, and contrasted with the proprietary beforeunload event.

As there are many potential security problems related to the execution of a task when the user asked to end the page (and thus the script), this will probably be unreliable until (and if) a serious normalization effort is done to precise what exactly can be done in a onbeforeunload callback.

For the predictable future, it's recommended to not depend on onbeforeunload but to use other schemes, for example constant background saving or a big "save" button.




回答2:


Try window.onbeforeunload. I found this in the jQueryBug Tracker as a possible solution:

window.onbeforeunload = function() { return "text"; }


来源:https://stackoverflow.com/questions/11317573/how-to-make-a-cross-browser-on-window-unload-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!