The principle is to detect the browser window size at this time through the onunload trigger time of leaving the page behavior time. Based on the size, it can be judged whether the user refreshes, jumps or closes the behavior program
The code is as follows
window.onunload = function(){ var a_n = window.event.screenX - window.screenLeft; var a_b = a_n > document.documentElement.scrollWidth-20; if(a_b && window.event.clientY< 0 || window.event.altKey){ alert('关闭页面行为'); }else{ alert('跳转或者刷新页面行为'); } }
It works well when using the close button in the upper right corner of the browser, but it doesn’t work when closing on a tab or closing on the taskbar.
js tag only has onloadonunloadonbeforeunload event but no onclose event.
The onunload event will be executed regardless of whether the page is closed or refreshed.
How to capture the page closing?
Onload is executed when the page is loaded
Onunload is executed only when the page is closed
Onbeforeunload is executed first, then onunload, and finally onload is executed when the page is refreshed.
In this way we can add a mark in onbeforeunload and judge the mark in onunload to determine whether the page is really closed
More complete compatibility with ff
The code is as follows
document.documentElement.scrollWidth-20; if(b && evt.clientY
The above method cannot judge multi-tab browsers, such as 360, ie8, etc. Let’s look at the
code below As follows
function CloseOpen(event) { if(event.clientX<=0 || event.clientY0)&&(event.clientX < document.body.clientWidth)) { s0 += "刷新窗口!"; } else { //获取当前时间 var date=new Date(); //将date设置为过去的时间 alert("关闭网页"); date.setTime(date.getTime()-10000); //将userId这个cookie删除 document.cookie="zhuangtao;expire="+date.toUTCString(); document.cookie="quanxianzifucuan;expire="+date.toUTCString(); document.cookie="quanxian;expire="+date.toUTCString(); s0 += "关闭窗口!"; sw = 1; } } } if (sw == 1) { event.returnValue = ""; } else { currentKeyCode = -1; } }
The above only cannot be used and the taskbar is closed, which basically meets our requirements.
The above content is the javascript introduced in this article to determine whether the web page is closed or refreshed. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!