【问题标题】:Page redirect after beforeunload event incorrectbeforeunload 事件后的页面重定向不正确
【发布时间】:2019-01-30 12:57:08
【问题描述】:

我有一个链接logout,它重定向到login.jsp。现在,假设我的 URL 是http://localhost/path1/path2/login.jsp。在beforeunload 被触发并单击leave page 后,页面重定向到http://localhost/path1/login.jsp。我不明白事件beforeunload 和实际页面重定向之间发生了什么。请参阅下面的代码

ma​​in.js

$(function(){
 $(window).bind("beforeunload", function(event) {
    if (hasChanges) {
     return "There are modifications, Are you sure?";
    }
 });

 $("#linkLogout").click(function(){
   //do something to backend
   postThis()
   window.location = "login.jsp";
 })
});

另外,我还测试了一个没有 midification 的场景,意思是上面代码中的hasChangesfalsewindow.location 正确重定向。

注意

  1. 请假设以上代码是旧代码
  2. 这只发生在 Firefox 浏览器上,令人惊讶的是它适用于 Edge 和 IE

更新

postThis 在其定义中执行 form.submit() 到 /path/backend。如果我的知识是正确的,执行表单 submit() 会对当前页面做一些事情。

【问题讨论】:

  • 因为 beforeunload 在 Firefox 中不起作用。在卸载前使用这个
  • 哦,你的意思是$(window).on("beforeunload",callback)
  • 所以当您已经在localhost/path1/path2/login.jsp 页面中时,您的window.location = "login.jsp" 会将您重定向到localhost/path1/login.jsp 而不是localhost/path1/path2/login.jsp
  • 是的,这是正确的。例如,在其他链接上,它只是localhost/path1/path2/otherlink.jsp。此问题特定于登录链接
  • 对不起,我在旧代码中发现了一些东西,请参阅更新。

标签: javascript jquery onbeforeunload


【解决方案1】:

试试这个对所有人都有效

window.onbeforeunload = function (e) {
  var e = e || window.event;

  // For IE and Firefox
  if (e) {
    e.returnValue = 'Any string';
  }

  // For Safari
  return 'Any string';
};

参考this

【讨论】:

  • 在上面尝试过,重定向仍然被破坏,我总是以http://localhost/path1/login.jsp 结束,这是一个在我的案例中找不到的页面。
  • 不正确的链接应该是http://localhost/path1/path2/login.jsp
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-29
  • 2017-01-18
  • 2011-08-11
  • 2018-06-08
  • 2013-06-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多