【问题标题】:javascript - Alert when Browser/tab close detectionjavascript - 浏览器/标签关闭检测时发出警报
【发布时间】:2013-11-11 13:36:33
【问题描述】:

当我点击链接刷新关闭标签时,我有此代码提醒。
但我需要 onlyclose 窗口(选项卡)上发出警报。如何做到这一点?
我的网站上有许多外部和内部链接。

<html>
    <head>
        <script type="text/javascript">
            window.onbeforeunload = function (e) {
                var e = e || window.event;
                //IE & Firefox
                if (e) {
                    e.returnValue = 'Are you sure?';
                }
                // For Safari
                 return 'Are you sure?';
            };
        </script>
    </head>
    <body>

        <!-- this will ask for confirmation: -->
       <!-- I need to alert for external links. -->
        <a href="http://google.com">external link</a>


       <!-- this will ask for confirmation: -->
<!-- I don't need to alert for local links in my web site -->
            <a href="about.html">internal link</a>
    </body>
</html>

【问题讨论】:

  • 你可以在 link-onclick 调用一个监听器来重置你的 onbeforeunload 监听器。
  • 我可以将 onclick 事件添加到将 onbeforeunload 设置为 null 的每个链接。但是我有很多链接。
  • 哦,你的意思是只关闭,而不是点击链接时?所以我想你应该在你的例子中添加另一个“本地链接”与 cmets“这个不会问”
  • 是的,仅对关闭和外部链接发出警报。

标签: javascript jquery window alert


【解决方案1】:

document.activeElement 在这种情况下很方便,它将等于您单击以卸载页面的链接。然后,您可以检查链接的href 属性是否包含您的主机名。 codepen.io 的一个示例是 (demo here):

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

  if(element.tagName === 'A' && element.href.indexOf('codepen.io/') === -1) {
    //IE & Firefox
    if (e) {
      e.returnValue = 'Are you sure?';
    }
    // For Safari
    return 'Are you sure?';
  }
};

我最初的想法是为http://https:// 做一个正则表达式,以查看路径是否是相对的,但看起来浏览器基本上将相对路径转换为绝对路径并在 http 前添加...

如果您想编写此代码使其更通用,您可以使用location.hostname 而不是静态输入主机名来进行比较。

最后,您在 IE 中的使用量可能会有所不同,具体取决于您希望支持哪些 IE,上述代码可能需要更新。现在的趋势是支持 IE11+ :)

【讨论】:

  • 非常感谢。工作正常。
猜你喜欢
  • 2010-11-17
  • 2022-01-12
  • 1970-01-01
相关资源
最近更新 更多