Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
23
rated 0 times [  24] [ 1]  / answers: 1 / hits: 33896  / 12 Years ago, fri, february 8, 2013, 12:00:00

I have one problem, I have a javascript function which I want to use when the browser is closed, How can I detect that a browser is being closed?



I have made some research on that I got solution like onunload or beforeunload but both the functions are being executed when I am reloading the page, Is there any solution that I can differentiate reload and browser/tab close.


More From » jquery

 Answers
18

answer is,



</head>
<html>
<head>
<script type=text/javascript src=http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js></script>
<script type=text/javascript language=javascript>

var validNavigation = false;

function endSession() {
// Browser or broswer tab is closed
// Do sth here ...
alert(bye);
}

function wireUpEvents() {
/*
* For a list of events that triggers onbeforeunload on IE
* check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
*/
window.onbeforeunload = function() {
if (!validNavigation) {
endSession();
}
}

// 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>
<h1>Eureka!</h1>
<a href=http://www.google.com>Google</a>
<a href=http://www.yahoo.com>Yahoo</a>
</body>
</html>

[#80353] Wednesday, February 6, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
noa

Total Points: 579
Total Questions: 83
Total Answers: 93

Location: Sweden
Member since Mon, Aug 10, 2020
4 Years ago
;