利用js实现页面关闭时发送http请求

2023-02-26,,

一、背景
假设有一个图片浏览的网页,每日pv量大概在80,000,000左右,uv量在3,000,000左右,现需要统计每张图片的pv量。
二、方案
方案1 每浏览一张图片,发送图片id和浏览数量到后台,并记录到数据库(可能会涉及到缓存机制,比如Memcache)
方案2 在页面中用js记录用户访问每张图片的次数,在用户关闭网页或刷新页面时,发送图片id和浏览数量到后台,并记录到数据库(可能会涉及到缓存机制,比如Memcache)
分析:
方案1中,需要发送大概80,000,000次(pv量)数据到后台,而方案2中只需要发送3,000,000次(uv量)数据,降低了1个数量级,这大大减轻了接入层机器的负载
三、实现
采用方案2。需要根据用户的关闭网页行为做js事件触发,此处我们用到onbeforeunload事件。

代码如下:

  1. <script>  
  2. var g_img_pv = {};  //用于记录图片id和点击次数  
  3.   
  4. function Fempty(v){  
  5.     if(v!=null && (typeof(v)=='object' || typeof(v)=='function')) return false;  
  6.     return ((""==v || undefined==v || null==v)?true:false);  
  7. }  
  8. function FaddEvent(e,evt,fn,isID)  
  9. {  
  10.     if(isID==true) e=Fid(e);  
  11.     if(!Fempty(e.attachEvent) && (typeof(e.attachEvent)=="function" || typeof(e.attachEvent)=="object"))  
  12.         e.attachEvent("on"+evt,fn);  
  13.     else if(!Fempty(e.addEventListener) && (typeof(e.addEventListener)=="function" || typeof(e.addEventListener)=="object"))  
  14.         e.addEventListener(evt,fn,false);  
  15. }  
  16. function stat_img_pv()  
  17. {  
  18.     if(!g_img_pv)  
  19.     {  
  20.         return;  
  21.     }  
  22.     var ids = '', counts = '';  
  23.     for(var picid in g_img_pv)  
  24.     {  
  25.         if(parseInt(picid) == picid)  
  26.         {  
  27.             ids += picid + ',';  
  28.             counts += g_img_pv[picid] + ',';  
  29.         }  
  30.     }  
  31.     ids = ids.substring(0, ids.length-1);  
  32.     counts = counts.substring(0, counts.length-1);  
  33.   
  34.     var url = 'http://www.example.com/statimgpv.php?'+ids+'&counts='+counts+'&t='+Math.random();  
  35.     var img = new Image();  
  36.     img.src = url;  
  37.     setTimeout(function(){},1000);  
  38. }  
  39. FaddEvent(window, 'beforeunload', stat_img_pv, false);  
  40. </script>  



写到这里好像是完成了,运行一下试试,用httpwatch抓一下包看看http请求是否成功。悲剧,在ie和firefox下,http请求被aborted了,截图如下:



这是怎么回事呢?个人认为,在设置完img变量的src属性后,并没有立即触发http请求,这样,当onbeforeunload响应完成,然后是响应onunload,接着页面就关闭了,这就导致了我们的img.src还没有被触发。
怎么办呢?第一个反应是在设置完img变量的src属性后,sleep一会,从而等待http请求被触发。但是js里貌似没有sleep函数,怎么办?
一种笨方法:
在img.src = url;后,加一个长时间的操作,比如加一个for循环,这样不就达到了延迟的目的了吗?试一下,firefox下ok,ie下,不好使…… 万恶的ie啊!

下面给出一种解决办法(在ie和firefox下测试均ok):

  1. function stat_img_pv()  
  2. {  
  3.     ……  
  4.     var img = new Image();  
  5.     img.src = url;  
  6.     setTimeout(function(){},1000);  //就是加入这一行!  
  7. }  



但是为啥好使我就不知道了,很偶然的尝试下发现ok。等待大牛的解答!


附 
onbeforeunload与onunload事件
onunload,onbeforeunload都是在刷新或关闭时调用,可以在<script>脚本中通过 window.onunload来指定或者在<body>里指定。区别在于onbeforeunload在onunload之前执行,它还可以阻止onunload的执行。
onbeforeunload也是在页面刷新或关闭时调用,onbeforeunload是正要去服务器读取新的页面时调用,此时还没开始读取;而onunload则已经从服务器上读到了需要加载的新的页面,在即将替换掉当前页面时调用。onunload是无法阻止页面的更新和关闭的。而onbeforeunload可以做到。
1、onbeforeunload事件:
说明:目前三大主流浏览器中firefox和IE都支持onbeforeunload事件,opera尚未支持。
用法:
·object.onbeforeunload = handler
·<element onbeforeunload = "handler" … ></element>
描述:
事件触发的时候弹出一个有确定和取消的对话框,确定则离开页面,取消则继续待在本页。handler可以设一个返回值作为该对话框的显示文本。
触发于:
·关闭浏览器窗口
·通过地址栏或收藏夹前往其他页面的时候
·点击返回,前进,刷新,主页其中一个的时候
·点击 一个前往其他页面的url连接的时候
·调用以下任意一个事件的时候:click,document write,document open,document close,window close ,window navigate ,window NavigateAndFind,location replace,location reload,form submit.
·当用window open打开一个页面,并把本页的window的名字传给要打开的页面的时候。
·重新赋予location.href的值的时候。
·通过input type=”submit”按钮提交一个具有指定action的表单的时候。
可以用在以下元素:
·BODY, FRAMESET, window
平台支持:
IE4+/Win, Mozilla 1.7a+, Netscape 7.2+, Firefox0.9+
示例:

  1. <html xmlns="http://www.w3.org/1999/xhtml">  
  2. <head>  
  3. <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />  
  4. <title>onbeforeunload测试</title>  
  5. <script>  
  6. function checkLeave(){  
  7.       event.returnValue="确定离开当前页面吗?";  
  8. }  
  9. </script>  
  10. </head>  
  11. <body onbeforeunload="checkLeave()">  
  12. </body>  
  13. </html>  



但是onbeforeunload有个小毛病,就是页面刷新时,他还是会调用到onbeforeunload,为什么?其实刷新就相当于关闭了这个IE再重新打开的意思,因此还是会调用到onbeforeunload。
究竟怎么解决刷新不调用onbeforeunload呢?网上提供很多方法,本人觉得最实用还是以下这段JS

  1. window.onbeforeunload = function(){     
  2.       var n = window.event.screenX - window.screenLeft;     
  3.       var b = n > document.documentElement.scrollWidth-20;     
  4.       if(b && window.event.clientY<0 || window.event.altKey)     
  5.       {     
  6.           alert("是关闭而非刷新");     
  7.           window.event.returnValue = "是否关闭?";  
  8.       }else{  
  9.           alert("是刷新而非关闭");     
  10.       }     
  11. }  



2、onunload事件
用法:
·object.onunload = handler
·<element onunload = "handler"></element>
描述:
当用户关闭一个页面时触发 onunload 事件。
触发于:
·关闭浏览器窗口
·通过地址栏或收藏夹前往其他页面的时候
·点击返回,前进,刷新,主页其中一个的时候
·点击一个前往其他页面的url连接的时候
·调用以下任意一个事件的时候:click,document write,document open,document close,window close ,window navigate ,window NavigateAndFind,location replace,location reload,form submit.
·当用window open打开一个页面,并把本页的window的名字传给要打开的页面的时候。
·重新赋予location.href的值的时候。
·通过input type=”submit”按钮提交一个具有指定action的表单的时候。
示例:

  1. <html xmlns="http://www.w3.org/1999/xhtml">  
  2. <head>  
  3. <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />  
  4. <title>onunload测试</title>  
  5. <script>  
  6. function checkLeave(){  
  7. alert("欢迎下次再来!");  
  8. }  
  9. </script>  
  10. </head>  
  11. <body onunload="checkLeave()">  
  12. </body>  
  13. </html>