javascript-浏览器/选项卡关闭检测时发出警报
我有此代码,当我单击链接时会发出警报或刷新或关闭选项卡javascript-浏览器/选项卡关闭检测时发出警报,javascript,jquery,window,alert,Javascript,Jquery,Window,Alert,我有此代码,当我单击链接时会发出警报或刷新或关闭选项卡 但我只需要在关闭窗口(选项卡)上发出警报。如何做到这一点?我的网站上有许多外部和内部链接 <html> <head> <script type="text/javascript"> window.onbeforeunload = function (e) { var e = e || window.event;
但我只需要在关闭窗口(选项卡)上发出警报。如何做到这一点?
我的网站上有许多外部和内部链接
<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>
window.onbeforeunload=函数(e){
var e=e | | window.event;
//IE和Firefox
如果(e){
e、 returnValue='您确定吗?';
}
//狩猎旅行
返回“您确定吗?”;
};
文档。activeElement
在这种情况下非常方便,它相当于您单击以卸载页面的链接。然后,您可以检查链接的href
属性是否包含您的主机名。codepen.io的一个例子是():
我最初的想法是为http://
和https://
做一个正则表达式,看看路径是否是相对的,但看起来浏览器基本上将相对路径转换为绝对路径,并在http之前加上前缀
如果要编写此代码,使其更通用,可以使用location.hostname
,而不是静态键入主机名进行比较
最后,您在IE中的相似性可能会有所不同,这取决于您希望支持上述代码的IE可能需要更新。现在的趋势是支持IE11+:)你可以在link onclick调用一个监听器,重置你的onbeforeunload监听器。我可以在每个链接中添加onclick事件,将onbeforeunload设置为null。但是我有很多链接。哦,你是说只有onclose,而不是在单击链接时?因此,我认为您应该在示例中添加另一个“本地链接”,带有注释“this one will not ask”是的,仅对onclose和外部链接发出警告。非常感谢。很好。
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?';
}
};