Trying to detect browser close event

JavascriptJqueryBrowser

Javascript Problem Overview


I have tried many methods to detect browser close event through jQuery or JavaScript. But, unfortunately, I have not been able to detect the close. The onbeforeunload and onunload methods are also not working.

How do I detect the window close, unload, or beforeunload events?

Javascript Solutions


Solution 1 - Javascript

Have you tried this code?

window.onbeforeunload = function (event) {
	var message = 'Important: Please click on \'Save\' button to leave this page.';
	if (typeof event == 'undefined') {
		event = window.event;
	}
	if (event) {
		event.returnValue = message;
	}
	return message;
};

$(function () {
	$("a").not('#lnkLogOut').click(function () {
		window.onbeforeunload = null;
	});
	$(".btn").click(function () {
		window.onbeforeunload = null;
});
});

The second function is optional to avoid prompting while clicking on #lnkLogOut and .btn elements.

One more thing, The custom Prompt will not work in Firefox (even in latest version also). For more details about it, please go to this thread.

Solution 2 - Javascript

Referring to various articles and doing some trial and error testing, finally I developed this idea which works perfectly for me.

The idea was to detect the unload event that is triggered by closing the browser. In that case, the mouse will be out of the window, pointing out at the close button ('X').

$(window).on('mouseover', (function () {
    window.onbeforeunload = null;
}));
$(window).on('mouseout', (function () {
    window.onbeforeunload = ConfirmLeave;
}));
function ConfirmLeave() {
    return "";
}
var prevKey="";
$(document).keydown(function (e) {            
    if (e.key=="F5") {
        window.onbeforeunload = ConfirmLeave;
    }
    else if (e.key.toUpperCase() == "W" && prevKey == "CONTROL") {                
        window.onbeforeunload = ConfirmLeave;   
    }
    else if (e.key.toUpperCase() == "R" && prevKey == "CONTROL") {
        window.onbeforeunload = ConfirmLeave;
    }
    else if (e.key.toUpperCase() == "F4" && (prevKey == "ALT" || prevKey == "CONTROL")) {
        window.onbeforeunload = ConfirmLeave;
    }
    prevKey = e.key.toUpperCase();
});

The ConfirmLeave function will give the pop up default message, in case there is any need to customize the message, then return the text to be displayed instead of an empty string in function ConfirmLeave().

Solution 3 - Javascript

Try following code works for me under Linux chrome environment. Before running make sure jquery is attached to the document.

$(document).ready(function()
{
	$(window).bind("beforeunload", function() { 
	    return confirm("Do you really want to close?"); 
	});
});

For simple follow following steps:

  1. open http://jsfiddle.net/
  2. enter something into html, css or javascript box
  3. try to close tab in chrome

It should show following picture:

enter image description here

Solution 4 - Javascript

Hi i got a tricky solution, which works only on new browsers:

just open a websocket to your server, when the user closes the window, the onclose event will be fired

Solution 5 - Javascript

Following script will give message on Chrome and IE:

<script>
window.onbeforeunload = function (e) {
// Your logic to prepare for 'Stay on this Page' goes here 

    return "Please click 'Stay on this Page' and we will give you candy";
};
</script>

Chrome
enter image description here

IE
enter image description here

on Firefox you will get generic message

enter image description here

Mechanism is synchronous so no server calls to delay will work, you still can prepare a mechanism like modal window that is shown if user decides to stay on page, but no way to prevent him from leaving.

Response to question in comment

F5 will fire event again, so will Atl+F4.

Solution 6 - Javascript

As Phoenix said, use jQuery .bind method, but for more browser compatibility you should return a String,

$(document).ready(function()
{
    $(window).bind("beforeunload", function() { 
        return "Do you really want to close?"; 
    });
});

more details can be found at : developer.mozilla.org

Solution 7 - Javascript

jQuery .bind() has been deprecated. Use .on() instead

$(window).on("beforeunload", function() {
    runBeforeClose();
});

Solution 8 - Javascript

Maybe it's better to use the path detecting mouse.

In BrowserClosureNotice you have a demo example and pure javascript library to do it.

It isn't perfect, but avoid problems of document or mouse events...

Solution 9 - Javascript

<script type="text/javascript">
window.addEventListener("beforeunload", function (e) {
	
  var confirmationMessage = "Are you sure you want to leave this page without placing the order ?";
  (e || window.event).returnValue = confirmationMessage;
  return confirmationMessage;
  
});
</script>

Please try this code, this is working fine for me. This custom message is coming into Chrome browser but in Mozilla this message is not showing.

Solution 10 - Javascript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />


<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) {
	  
	  		var ref="load";
	  $.ajax({
            type: 'get',
            async: false,
            url: 'logout.php',
 data:
            {
                ref:ref               
            },
			 success:function(data)
            {
				console.log(data);
			}
            });
     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> 

This is used for when logged in user close the browser or browser tab it will automatically logout the user account...

Solution 11 - Javascript

You can try something like this.

<html>
<head>
    <title>test</title>
    <script>
        function openChecking(){
            // alert("open");
            var width = Number(screen.width-(screen.width*0.25));  
            var height = Number(screen.height-(screen.height*0.25));
            var leftscr = Number((screen.width/2)-(width/2)); // center the window
            var topscr = Number((screen.height/2)-(height/2));
            var url = "";
            var title = 'popup';
            var properties = 'width='+width+', height='+height+', top='+topscr+', left='+leftscr;
            var popup = window.open(url, title, properties);
            var crono = window.setInterval(function() {
                if (popup.closed !== false) { // !== opera compatibility reasons
                    window.clearInterval(crono);
                    checkClosed();
                }
            }, 250); //we check if the window is closed every 1/4 second
        }	
        function checkClosed(){
            alert("closed!!");
            // do something
        }
    </script>    
</head>
<body>
    <button onclick="openChecking()">Click Me</button>
</body>
</html>

When the user closes the window, the callback will be fired.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionvjetaView Question on Stackoverflow
Solution 1 - JavascriptRavimallyaView Answer on Stackoverflow
Solution 2 - JavascriptshivView Answer on Stackoverflow
Solution 3 - JavascriptKhamidullaView Answer on Stackoverflow
Solution 4 - JavascriptwutzebaerView Answer on Stackoverflow
Solution 5 - JavascriptMatas VaitkeviciusView Answer on Stackoverflow
Solution 6 - JavascriptMacondoView Answer on Stackoverflow
Solution 7 - Javascriptow3nView Answer on Stackoverflow
Solution 8 - JavascriptmanufoselaView Answer on Stackoverflow
Solution 9 - Javascriptuser2753425View Answer on Stackoverflow
Solution 10 - Javascriptramesh kannaView Answer on Stackoverflow
Solution 11 - JavascriptSalvador P.View Answer on Stackoverflow