是否可以使用
javascript禁用任何使浏览器远离当前页面的代码?
我已经尝试了以下代码,但它没有工作:
- $(window).unload(function(e){
- event.stopPropagation();
- event.preventDefault();
- return false;
- });
我猜这个代码不起作用,因为在卸载()的时候,太晚了.
任何其他想法?
解决方法
您可以在浏览器中弹出一条消息,询问用户是否希望离开页面.这适用于强制浏览器离开当前页面的所有事件(甚至提交表单并关闭浏览器).
测试页:http://dl.dropbox.com/u/3937673/test.html
JavaScript的:
- window.onbeforeunload = function(e){
- var e = e || window.event;
- // For IE and Firefox (prior to 4)
- if (e){
- e.returnValue = 'Do you want to leave this page?';
- }
- // For Safari and Chrome
- return "Do you want to leave this page?";
- };
或者用jQuery:
- $(window).bind('beforeunload',function(){
- return "Do you want to leave this page?";
- });