我希望每当用户离开我的网站(不仅仅是网页,整个网站)时,都应该给用户一个弹出窗口。
我已经实现了一种方法,但每次导航离开网页时都会弹出。
window.onbeforeunload = function (evt) {
var message = 'Are you sure you want to navigate away from myWEbSite?';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt ) {
evt.returnValue = message;
}
return message;
}
答案 0 :(得分:0)
您无法获取新的目标网址,因为这是受保护的信息(请参阅How can i get the destination url in javascript onbeforeunload event?)
因此,如果访问者离开网站,您将无法看到。
替代方案:您可以听取引用其他网页的超链接的所有点击,并实现捕获外部链接的功能。
答案 1 :(得分:0)
您可以玷污自己的JQuery选择器,如下所示:
$.expr[':'].external = function(obj){
return !obj.href.match(/^mailto\:/) && (obj.hostname != location.hostname);
};
$.expr[':'].internal = function(obj){
return obj.hostname == location.hostname;
};
然后您可以执行以下操作:
$(function() {
var unloadMessage = function() {
return "Are you sure you want to navigate away from myWEbSite?";
};
$('a:internal').click(function() {
window.onbeforeunload = null;
});
$('form').submit(function() {
window.onbeforeunload = null;
});
$('a:external').click(function() {
window.onbeforeunload = unloadMessage;
});
window.onbeforeunload = unloadMessage;
});
在特定情况下,只需点击导航链接或提交内部表单,您就需要设置window.onbeforeunload == null
。