这个脚本挑战吸引了我的注意力。
感谢 Sandra,在无聊的周一晚上,她给了我一个有趣的代码时间。
首先,我想到了 (因为我在某处读过它......我不知道什么时候) beforeunload 事件的处理方式不同取决于浏览器,因此不是一个安全的选择。
例如,Chrome 不允许在该事件上使用 alert 或 prompt,而这正是您尝试过的。
但它仍然允许函数运行。
基于this old answer,我为你测试了一些东西。
截至 2017 年,返回的消息(如 2012 年答案中所建议的那样)未显示在 Chrome 中。
但是 return true; 可以正常使用默认的 Chrome 消息:
现在,如果触发事件的目标是内部链接,您不希望执行绑定到beforeunload 事件的函数。
我已经添加了到要求:“不在页面刷新!”
(keydown on F5)
好的。
这就是我现在所拥有的,仅在关闭选项卡/浏览器和外部链接点击时触发。
(考虑完整和/或相对 URL)。
我只在 Chrome 上进行了测试,我认为这是这次事件中最严重的。
它正在工作。
并且此代码完全符合"Rubber Duck"。
干杯!
;)
$(document).ready(function(){
console.log("Page has just loaded.");
// Flag to determine if a link click is local or external.
window.localLinkClicked = false;
// flag for the refresh key [F5]
var refreshKey=false;
// Link click handler.
$("a").on("click", function(e) {
// Get the link URL
var url = $(this).attr("href");
console.log("Link clicked. URL: "+url);
// Check if the link is relative to your domain:
// [SUB_DOMAIN] example: www
// [DOMAIN] example: google
// [TLD] example: com
// This regexp (regular expression) takes in account secured and unsecured domains (http:// and https://)
if ( !/^(http)(s?):\/\//.test(url) || /^(http)(s?):\/\/[SUB-DOMAIN]\.[DOMAIN]\.[TLD]\//.test(url) ) {
window.localLinkClicked = true;
}else{
window.localLinkClicked = false;
}
console.log("Local click ? " + window.localLinkClicked);
if (!window.localLinkClicked) {
var leave = confirm("Do you really want to leave our website to follow this link?");
if(leave){
refreshKey=true;
alert("Okay, see you soon!");
}else{
e.preventDefault();
console.log("User has cancelled his navigation.")
}
}
// Reset the local click flag
setTimeout(function(){
window.localLinkClicked = false;
},10);
});
// Handler to detect the refresh key
$(window).on("keydown",function(e){
//console.log(e.which);
if(e.which==116 ){
console.log("User is REFRESHING the page. Do not trigger the confirm to leave.");
refreshKey=true;
}else{
refreshKey=false;
}
});
// On beforeunload event handler.
$(window).on('beforeunload', function(e) {
if(typeof(e)!="undefined" && e.target.tagName!="undefined" && (!refreshKey && !window.localLinkClicked) ){
return true;
}
});
});