我有这个代码,当我单击链接 or refresh or 关闭选项卡.
但我需要警惕only on close窗口(选项卡)。这个怎么做?
我的网站上有许多外部和内部链接。
<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 的一个示例是(演示在这里 http://codepen.io/anon/pen/mVGjBO?editors=1010):
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://
and https://
查看路径是否是相对路径,但看起来浏览器基本上将相对路径转换为绝对路径并在前面添加 http...
如果您想编写此代码以使其更加通用,您可以使用location.hostname
而不是静态键入主机名进行比较。
最后,您在 IE 中的情况可能会有所不同,具体取决于您想要支持哪些 IE,上述代码可能需要更新。现在的趋势是支持IE11+:)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)