【问题标题】:How to call a function during window.onbeforeunload如何在 window.onbeforeunload 期间调用函数
【发布时间】:2018-02-16 20:26:17
【问题描述】:

我在这里阅读了很多关于如何拦截窗口关闭和弹出对话框的示例。我需要一些不同的东西。在我的页面关闭或更改之前,我需要调用并完成一个函数。

我更新了下面的代码,以帮助更好地解释我的问题。

window.addEventListener("beforeunload", function(event) {
  //I need the done callback function to fire before the page is changed
  //I've placed return null in that call because I think I need to pass something back?
  visualize({
    auth: {
      name: "piper",
      password: "password",
    }
  }, function(v) {
    //destroy session
    v.logout().done(function() {
      console.log("JRS Logout");
      return null;
    });
  });
});

【问题讨论】:

  • 向我们展示您尝试在 onbeforeunload 事件中调用它的位置,并准确描述您不理解的情况。
  • 是否有“window.onbeforeunload = jrsLogout;”的原因不行吗?
  • onbeforeunload 不能包含异步代码
  • @PatrickRoberts 我认为这就是我的问题。
  • 如果v.logout()同步启动一个注销请求,当它完成时你将无法做任何事情,因为页面已经卸载,但是任何同步发送的XHR请求仍然应该去通过并被服务器接收。所以你需要做的是visualize(..., function (v) { ... })inside回调,注册调用v.logout()beforeunload处理程序。

标签: javascript logout onbeforeunload visualize


【解决方案1】:

要跟进my comment,这就是我的建议:

visualize({
  auth: {
    name: "piper",
    password: "password",
  }
}, function(v) {
  //I need the done callback function to fire before the page is changed
  //I've placed return null in that call because I think I need to pass something back?
  window.addEventListener("beforeunload", function(event) {
    // make sure that this is reached
    console.log('JRS Logging Out');
    //destroy session
    v.logout().done(function() {
      // THIS WILL NEVER BE REACHED, but it should still work
      console.log("JRS Logout");
      return null;
    });
  });
});

我自己没有测试过这个,所以你不应该相信我的话它有效。确保在尽可能多的浏览器上对其进行测试,因为每个浏览器都可能会缓冲 XHR 请求并抢先取消它,而不是在页面卸载之前发送请求。

【讨论】:

  • 我认为正如你之前提到的,由于我的注销功能是异步的,它不允许这个过程工作。我已经尝试过您的代码,但 console.log 行永远不会被调用。
  • @user179981 不应该调用它。我要求您检查服务器是否收到请求,我说console.log()never 被调用,但是(可能取决于浏览器)它仍然应该成功注销.
猜你喜欢
  • 2023-02-04
  • 1970-01-01
  • 1970-01-01
  • 2021-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-01
相关资源
最近更新 更多