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.
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="确定要退出本页吗?"; }
2. Use the onUnload method
Add the onUnload event to the body tag
body onUnload="myClose()"
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.
<!doctype html> <html> <head> <meta charset="utf-8"> <title>导出数据</title> <script type="text/javascript"> if(top.location != self.location ) { top.location = self.location; } var time = 5; //时间,秒 function Redirect() { //window.location = "http://www.cssue.com/"; window.opener=null; window.open('','_self'); window.close(); } var i = 0; function dis() { if( i > time ) { Redirect(); } document.all.t.innerHTML = "还剩<span style='color:red'>" + (time - i) + "</span>秒,本页面将自动关闭"; i++; } timer = setInterval('dis()', 1000); //显示时间 timer = setTimeout('Redirect()', time * 1000); //跳转 </script> </head> <body > <div style="text-align:center;margin-top:5%"> <h1> <div id="s">Sorry ! 您输入的信息在服务器中无法找到</div> <div id="t"></div> </h1> </div> </body> </html>
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!