【问题标题】:Fire onbeforeunload confirm alert for external sites only仅针对外部站点触发 onbeforeunload 确认警报
【发布时间】:2015-06-07 02:53:51
【问题描述】:

如果用户离开网站,我正在使用 window.onbeforeunload 方法显示确认消息。

window.onbeforeunload = function(e) {
    return textMsg;
};

但只有当用户导航到外部网站或关闭窗口时,我才需要触发它。

那么如何取消同一域内所有 XHR 的确认消息和表单提交等?

【问题讨论】:

标签: javascript angularjs onbeforeunload


【解决方案1】:

尝试(未经测试的代码):

window.onbeforeunload = function(e) {
    return textMsg;
};

$('a:not([href^="http"])').on('click', function() {
    window.onbeforeunload = null; // prevent message
});

$('form').on('submit', function() {
    window.onbeforeunload = null; // prevent message
});

如果链接不以http(外部链接)开头并且提交<form>,这将阻止事件触发。目前正在寻找关闭窗口的解决方案。

【讨论】:

  • 使用window.location怎么样?它也不应该出现。
  • 你会用它做什么?
  • 我同时使用链接和 window.location 来重定向到响应 url。如果我选择元素 byTagName ,则 href 方法返回带有 http 的完整网址
  • 解决方案有效。但是有什么方法可以取消页面刷新时的弹出窗口吗?
  • 谢谢,解决方案有帮助。最后我们跳过了检测浏览器刷新
猜你喜欢
  • 2018-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-23
  • 2020-03-19
  • 1970-01-01
  • 2012-12-27
相关资源
最近更新 更多