gpt4 book ai didi

javascript - 浏览器/选项卡关闭检测时发出警报

转载 作者:行者123 更新时间:2023-11-30 06:53:54 32 4
gpt4 key购买 nike

当我点击链接刷新关闭标签页时,我有这段代码会发出警报。
但我需要在关闭 窗口(选项卡)上 发出警报。怎么做?
我的网站上有很多外部和内部链接。

<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>

最佳答案

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+:)

关于javascript - 浏览器/选项卡关闭检测时发出警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19708350/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com