admin管理员组文章数量:1203387
Is there a way to trap the browser closing event from JavaScript? I don't want to do this in Page Unload event or anything. It must be handled on clicking the browser close button.
Is it possible?
Is there a way to trap the browser closing event from JavaScript? I don't want to do this in Page Unload event or anything. It must be handled on clicking the browser close button.
Is it possible?
Share Improve this question edited Jun 23, 2011 at 14:12 Bill the Lizard 406k211 gold badges572 silver badges889 bronze badges asked Jul 17, 2009 at 13:15 RameshVelRameshVel 65.9k32 gold badges172 silver badges213 bronze badges5 Answers
Reset to default 13No. You only have onbeforeunload
event, available as raw javascript (jquery doesn't include this event).
If you want to try it, try to post here an answer and, without pressing "post your answer" try to close the browser window.
This is the closest way to access the "close window" event.
onbeforeunload event captures every unload event but there is some trick way to handle if user closing browser by clicking close button, here is a sample code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
//handle if your mouse is over the document body,
//if not your mouse is outside the document and if you click close button return message or do what you want
var out = false;
$("body").mouseover(function(){
out=false;
}).mouseout(function(){
out=true;
});
$(window).bind('beforeunload', function(e){
if(out)
{return "Do you really want to leave this page now?"}
});
});
</script>
</head>
<body>
<p>
<a href="http://cssbased.com">go outside</a>
<br>
<a href="test.html">reload page</a>
<span> </span>
</p>
</body>
</html>
Here is nice article about this from 4guysfromrolla
<script language="JavaScript">
window.onbeforeunload = confirmExit;
function confirmExit()
{
return message to display in dialog box;
}
</script>
Not really. Page unload event is all you have. And even that not always. It would provide the ability to interfere with user's wishes pretty bad.
you can not call alert or any interface(like open modal dialog or something!) while closing, but you do something in background for sure with this function
window.onunload = function()
{
if ((window.event.clientX < 0) || (window.event.clientY<0)) // close button
{
//do something on closing event
}
else if (window.event.altKey == true) // ALT + F4
{
//do something on closing event
}
else // for all other unload events
{
//do something on closing event
}
}
本文标签: Handle Browser close in JavaScriptStack Overflow
版权声明:本文标题:Handle Browser close in JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738579612a2101081.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论