onunload
(or onbeforeunload
) cannot redirect the user to another page.
(onunload
(或onbeforeunload
)无法将用户重定向到另一个页面。)
This is for security reasons.(这是出于安全原因。)
If you want to show a prompt before the user leaves the page, use onbeforeunload
:
(如果要在用户离开页面之前显示提示,请使用onbeforeunload
:)
window.onbeforeunload = function(){
return 'Are you sure you want to leave?';
};
Or with jQuery:
(或者使用jQuery:)
$(window).bind('beforeunload', function(){
return 'Are you sure you want to leave?';
});
This will just ask the user if they want to leave the page or not, you cannot redirect them if they select to stay on the page.
(这只会询问用户是否要离开页面,如果他们选择留在页面上,则无法重定向。)
If they select to leave, the browser will go where they told it to go.(如果他们选择离开,浏览器将转到他们告诉它去的地方。)
You can use onunload
to do stuff before the page is unloaded, but you cannot redirect from there (Chrome 14+ blocks alerts inside onunload
):
(您可以在卸载页面之前使用onunload
来执行操作,但是您无法从那里重定向(Chrome 14+会在onunload
阻止警报):)
window.onunload = function() {
alert('Bye.');
}
Or with jQuery:
(或者使用jQuery:)
$(window).unload(function(){
alert('Bye.');
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…