javascript-当浏览器/标签页关闭检测到时发出警报 [英] javascript - Alert when Browser/tab close detection
问题描述
我有此代码,当我单击链接或刷新或关闭标签时会发出警报.
但是我需要关闭窗口(标签)上的仅警报.
我的网站上有很多外部和内部链接.
I have this code that alert when I click a link or refresh or close tab.
But I need alert only on close window (tab). how to do this?
I have many external and internal links on my site.
<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(此处演示):
document.activeElement
is handy in this scenario, it will be equal to the link you click on to unload the page. You can then check the link's href
attribute whether it contains your host name. An example for codepen.io would be (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 ...之前加上
My initial thought was to do a regex for http://
and https://
to see if the path is relative but it looks like browsers basically convert relative paths to absolute and prepend the http...
如果要编写此代码以使其更通用,可以使用location.hostname
而不是静态键入主机名进行比较.
If you want to write this code so that it is more universal you can use location.hostname
instead of statically typing the hostname to do a comparison on.
最后,您的IE里程可能会有所不同,具体取决于您要支持上述代码的IE可能需要更新.当今的趋势是支持IE11 +:)
Finally, your milage may vary in IE depending on which IEs you want to support the above code might need updated. The trend nowadays is to support IE11+ :)
这篇关于javascript-当浏览器/标签页关闭检测到时发出警报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!