window.onunload | window.onbeforeunload

先引述一段jQuery 官方对于onunload的评述:

The unload event is sent to the window element when the user navigates away from the page. This could mean one of many things. The user could have clicked on a link to leave the page, or typed in a new URL in the address bar. The forward and back buttons will trigger the event. Closing the browser window will cause the event to be triggered. Even a page reload will first create an unload event.

The exact handling of the unload event has varied from version to version of browsers. For example, some versions of Firefox trigger the event when a link is followed, but not when the window is closed. In practical usage, behavior should be tested on all supported browsers, and contrasted with the proprietary beforeunload event.

Any unload event handler should be bound to the window object:

1
2
3
$( window ).unload(function() {
alert( "Handler for .unload() called." );
});

After this code executes, the alert will be displayed whenever the browser leaves the current page. It is not possible to cancel the unload event with .preventDefault(). This event is available so that scripts can perform cleanup when the user leaves the page.

 

解决兼容性:

   

1 var myEvent = window.attachEvent || window.addEventListener;
2     var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, IE8 compitable
3 
4             myEvent(chkevent, function(e) { // For >=IE7, Chrome, Firefox
5                 var confirmationMessage = 'Are you sure to leave the page?';  // a space
6                 (e || window.event).returnValue = confirmationMessage;
7                 return confirmationMessage;
8  });

 

转载于:https://www.cnblogs.com/yiliweichinasoft/p/4061737.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值