浏览器几乎不会允许onbeforeunload
这样做。哎呀,并不是所有人都支持它。我很确定 Opera 不会。
此事件的目的是显示一个确认框,询问您是否要离开。就是这样。您不能调用alert
或confirm
,重定向用户,进行(异步)AJAX 调用,或者做很多其他事情。
你可以做的是返回一个字符串。返回的字符串将显示在浏览器呈现的警报上,询问您是否要离开。注意:Firefox 不会真正显示您的字符串(请参阅错误# 588292)。
var internalLink = false;
function pageUnload() {
if (!internalLink && location.protocol != 'http:') {
internalLink = true;
var s = 'Alert Message';
// You cannot alert or set location.href here
// This will show your message in a confirm popup
return s;
}
}
window.onbeforeunload = pageUnload;
因此,正如您所看到的,浏览器对它们如何处理甚至触发onbeforeunload
. 谨慎使用。
没有“官方”方式可以知道用户是点击“离开”还是“留下”。事实上的方法是使用unload
事件和 a setTimeout
,但它非常hacky。
var internalLink = false,
stayTimeout, stayClicked;
function pageUnload() {
if(stayClicked){
// Don't run this multiple times
return;
}
if (!internalLink && location.protocol != 'http:') {
internalLink = true;
// To mark that we've ran this event once
stayClicked = true;
// If the user opted to stay, this will be ran
setTimeout(stayOnPage, 1000);
var s = 'Alert Message';
// You cannot alert or set location.href here
// This will show your message in a confirm popup
return s;
}
}
function stayOnPage(){
// The user opted to stay, do something
location.href= 'foo.com';
// If you are not going to redirect, set stayClicked to false
// otherwise leave it alone
// stayClicked = false;
}
function leavePage(){
// The user has chosen to leave the page, clear the timeout
clearTimeout(stayTimeout);
}
window.onbeforeunload = pageUnload;
window.unload = leavePage;
一个更好的解决方案是将事件分配给<a>
标签,使用你自己的confirm
盒子,然后做任何事情。
var a = document.getElementsByTagName('a');
for(var b in a){
a[b].addEventListener('click', function(e){
var c = confirm('Do you want to follow this link?');
if(c){
// The user wants to leave, let them
return true;
}
else{
// Otherwise block the link, and do whatever
e.preventDefault();
location.href= 'foo.com';
}
});
}