Home > Web Front-end > JS Tutorial > body text

How to capture window closing event in javascript

coldplay.xixi
Release: 2023-01-05 16:13:15
Original
3958 people have browsed it

How to capture the window closing event with javascript: 1. Use javascript to redefine the [window.onbeforeunload()] event; 2. Add the onUnload event to the body tag.

How to capture window closing event in javascript

The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, DELL G3 computer.

Javascript method to capture window closing event:

1. Use javascript to redefine the window.onbeforeunload() event

Just define a function in javascript

function window.onbeforeunload() { alert("Close the window")}

alert() event will be executed before closing the window, you can also The user decides whether to close the window

function window.onbeforeunload() { 
if (event.clientX>document.body.clientWidth && event.clientY<0 ||event.altKey) 
window.event.returnValue="确定要退出本页吗?"; 
}
Copy after login

2. Use the onUnload method

Add the onUnload event to the body tag

body onUnload="myClose()"
Copy after login

Then define myClose( in javascript ) method

But the onUnload method is executed after closing the window, not before closing the window. If you want to make a judgment before closing the window, please use the first method

the above two For the method to be able to successfully close the window, the window must be an independent new window; if it is based on a parent window, it cannot be closed.





导出数据


Sorry ! 您输入的信息在服务器中无法找到

Copy after login

Related free learning recommendations: javascript video tutorial

The above is the detailed content of How to capture window closing event in javascript. 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 [email protected]
Popular Tutorials
More>
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!