Home >Web Front-end >JS Tutorial >Detailed explanation of how JavaScript determines browser closure and event capture code

Detailed explanation of how JavaScript determines browser closure and event capture code

伊谢尔伦
伊谢尔伦Original
2017-07-24 09:58:264059browse

Since the browser is stateless, there will be two situations when capturing the browser closing at this time:

1. Really close the browser (a. Click Close button b. Right-click the taskbar to close c. Press alt+F4 to close)
2. Refresh the browser.
How to distinguish between these two actions?
Javascript code processing method:

function window.onbeforeunload() 
{ 
//用户点击浏览器右上角关闭按钮或是按alt+F4关闭 
if(event.clientX>document.body.clientWidth&&event.clientY<0||event.altKey) 
{ 
// alert("点关闭按钮"); 
document.getElementById("hiddenForm:hiddenBtn").click(); 
// window.event.returnValue="确定要退出本页吗?"; 
} 
//用户点击任务栏,右键关闭。s或是按alt+F4关闭 
else if(event.clientY > document.body.clientHeight || event.altKey) 
{ 
// alert("任务栏右击关闭"); 
document.getElementById("hiddenForm:hiddenBtn").click(); 
// window.event.returnValue="确定要退出本页吗?"; 
} 
//其他情况为刷新 
else 
{ 
// alert("刷新页面"); 
} 
}

Event.clientX mouse cursor X Coordinates
document.body.clientWidth Form client area width
event.clientY Mouse cursor Y coordinate
event.altKey Whether the alt key is pressed

Event capture method:

<body scroll="no" onbeforeunload="return CloseEvent();" onunload="UnLoadEvent()" > 
</body> 
<script language="JavaScript" type="text/javascript"> 
var DispClose = true; 
function CloseEvent() 
{ 
if (DispClose) 
{ 
return "是否离开当前页面?"; 
} 
} 
function UnLoadEvent() 
{ 
DispClose = false; 
//在这里处理关闭页面前的动作 
} 
</script>

The onbeforeunload event is triggered before the page is unloaded. If the user selects "Yes", it is determined that unloading the page will trigger the onunload event, otherwise the page will be returned without any operation.

The above is the detailed content of Detailed explanation of how JavaScript determines browser closure and event capture code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn