Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...