如何发出跨浏览器的窗口卸载请求? [英] How to make a cross-browser on-window-unload request?

查看:25
本文介绍了如何发出跨浏览器的窗口卸载请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Flash 游戏,我试图保存用户关闭浏览器选项卡时的状态.它使用以下 jquery 代码:

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:正常工作
  • Chrome:在重新加载时正常工作,但在关闭标签关闭浏览器
  • 时无法正常工作
  • IE(所有版本):根本不起作用
  • 我希望它在所有浏览器中都能正常工作,但最重要的是 Chrome(我们的用户中没有多少人拥有 IE).

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

    Flash 正确调用了 sendRequest(在所有浏览器中,通过警报进行了测试),所以我不认为问题来自 Flash,但它可能.

    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.

    推荐答案

    简短的回答是你不能.

    onbeforeunload 事件最初由 Microsoft 引入,以允许一个标准的确认对话框.现在大多数浏览器都以原始形式支持它,并且在大多数情况下,允许执行一个简短的非交互式函数(例如,您可以在 localStorage 中记录您的状态).但是,如跨浏览器 jQuery API 中所述,这是不可靠的:

    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 :

    卸载事件的确切处理因版本而异浏览器的版本.例如,某些版本的 Firefox 会触发跟踪链接时的事件,而不是关闭窗口时的事件.在实际使用,应在所有支持的浏览器上测试行为,并与专有的 beforeunload 事件形成对比.

    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.

    由于当用户要求结束页面(以及脚本)时,有许多与任务执行相关的潜在安全问题,这可能是不可靠的,直到(并且如果)认真地进行标准化工作以精确在 onbeforeunload 回调中究竟可以做什么.

    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.

    对于可预测的未来,建议不要依赖onbeforeunload,而是使用其他方案,例如恒定后台保存或一个大的保存"按钮.

    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.

    这篇关于如何发出跨浏览器的窗口卸载请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆