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

伊谢尔伦
Release: 2017-07-24 09:58:26
Original
3936 people have browsed it

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("刷新页面"); } }
Copy after login

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:

  
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!