Hai all,
How to Detect, the Client Closed the Browser/Tab using Javascript.
How to Detect, the Client Closed the Browser/Tab using Javascript.
function isUserClickedCloseButton()
{
var browserWindowWidth = 0;
var browserWindowHeight = 0;
// gets the width and height of the browser window
if (parseInt(navigator.appVersion) > 3)
{
if (navigator.appName == "Netscape")
{
browserWindowWidth = window.innerWidth;
browserWindowHeight = window.innerHeight;
}
if (navigator.appName.indexOf("Microsoft") !=- 1)
{
browserWindowWidth = top.window.document.body.offsetWidth;
browserWindowHeight = top.window.document.body.offsetHeight;
}
}
// checks if the X button was closed
// if event.clientY < 0, then click was on the browser menu area
// if event.screenX > (browserWindowWidth - 25), the X button was clicked
// use screenX if working with multiple frames
return (event.clientY < 0 && event.screenX > (browserWindowWidth - 25)) ? true : false;
}
<html>
<head>
<title>Detecting browser close in IE</title>
<script type="text/javascript" src="/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
var validNavigation = false;
function wireUpEvents() {
var dont_confirm_leave = 0; //set dont_confirm_leave to 1 when you want the user to be able to leave withou confirmation
var leave_message = 'ServerThemes.Net Recommend BEST WEB HOSTING at new tab window. Good things will come to you'
function goodbye(e) {
if (!validNavigation) {
window.open("/best-web-hosting-services","_blank");
return leave_message;
}
}
window.onbeforeunload=goodbye;
// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
validNavigation = true;
}
});
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
// Attach the event click for all inputs in the page
$("input[type=submit]").bind("click", function() {
validNavigation = true;
});
}
// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
wireUpEvents();
});
</script>
</head>
<body>
<p>
Check which action detects browser window close:
<ol>
<li>Click this <a href="#" onclick="location.reload();return false">Refresh</a> link or the browser's Refresh button</li>
<li>Navigate away from this page through a <a href="http://serverthemes.net/">link</a></li>
<li>Type another URL in the address bar</li>
<li>Click Back or Forward button</li>
<li>Click the Close (X) button in the top-rightmost corner of the browser</li>
<li>Click the IE icon in the top-leftmost corner and choose Close. Or simply double-click the icon</li>
<li>Press Alt+F4 key</li>
</ol>
</p>
<p>In IE, the last 3 actions are correctly detected by the <a href="#" onclick="alert(doUnload);return false">javascript code</a> inside this page as browser close.</p>
</body>
</html>
Comment