F5前的事件调用beforeunload和unload jquery捕获f5刷新事件 监听页面刷新

来源:互联网 发布:mac rebel什么质地 编辑:程序博客网 时间:2024/04/26 16:05

我们实现在刷新或关闭前弹出弹框显示提示文字很容易,例:

<!doctype html>  <html>   <head>    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">    <meta name="renderer" content="webkit">    <title>test</title>    <script type="text/javascript" src="skin/base2/js/jquery-1.11.3.min.js"></script>   </head>   <body>   </body>    <script>      ;$(function() {          $(window).on('beforeunload', function() {              return "您确定要离开吗?!";          });      });   </script>  </html>  

如果我们想要实现在刷新或关闭前调用某个方法就不行了,也许很多人尝试过了,使用如下方法:

$(window).on('beforeunload', function() {              alert(1);          });  

可是这种方法只在ie浏览器有效果。
解释:
1 其实beforeunload是起了作用的,只不过alert()弹框在浏览器中没有出现
2 测试这个,我们可以对后台发送请求,看看后台数据是否发生变化
3 beforeunload在ff中不兼容,我们同时可以加上unload事件(这两个事件的具体区别大家可以自行百度)
测试思路:

$(window).on('beforeunload unload', function() {                  $.ajax({  //发送请求,刷新一次,后台数据自增一次,大家查看后台数据就知道了,这两个事件是起了作用的  });              });  
阅读全文
0 0