jquery beforeunload when closing (not leaving) the page?

JavascriptJquery

Javascript Problem Overview


How can I display "Are you sure you want to leave the page?" when the user actually tries to close the page (click the X button on the browser window or tab) not when he tries to navigate away from the page (click on another link).

My client wants a message to appear when the user tries to close the page "Are you sure you want to leave the page? You still have items in your shopping cart."

Unfortunately $(window).bind('beforeunload') doesn't fire only when the user closes the page.

jQuery:

function checkCart() { 
  $.ajax({
    url : 'index.php?route=module/cart/check',
    type : 'POST',
    dataType : 'json',
    success : function (result) {
       if (result) {
        $(window).bind('beforeunload', function(){
          return 'leave?';
        });
       }
    }
  })
}

Javascript Solutions


Solution 1 - Javascript

You can do this by using JQuery.

For example ,

<a href="your URL" id="navigate"> click here </a>

Your JQuery will be,

$(document).ready(function(){

	$('a').on('mousedown', stopNavigate);

    $('a').on('mouseleave', function () {
	       $(window).on('beforeunload', function(){
	              return 'Are you sure you want to leave?';
           });
    });
});

function stopNavigate(){	
	$(window).off('beforeunload');
}

And to get the Leave message alert will be,

$(window).on('beforeunload', function(){
	  return 'Are you sure you want to leave?';
});

$(window).on('unload', function(){

         logout();

});

This solution works in all browsers and I have tested it.

Solution 2 - Javascript

Try javascript into your Ajax

window.onbeforeunload = function(){
  return 'Are you sure you want to leave?';
};

Reference link

Example 2:

document.getElementsByClassName('eStore_buy_now_button')[0].onclick = function(){
    window.btn_clicked = true;
};
window.onbeforeunload = function(){
    if(!window.btn_clicked){
        return 'You must click "Buy Now" to make payment and finish your order. If you leave now your order will be canceled.';
    }
};

Here it will alert the user every time he leaves the page, until he clicks on the button.

DEMO: http://jsfiddle.net/DerekL/GSWbB/show/

Solution 3 - Javascript

Credit should go here: https://stackoverflow.com/questions/15277403/how-to-detect-if-a-link-was-clicked-when-window-onbeforeunload-is-triggered

Basically, the solution adds a listener to detect if a link or window caused the unload event to fire.

var link_was_clicked = false;
document.addEventListener("click", function(e) {
   if (e.target.nodeName.toLowerCase() === 'a') {
      link_was_clicked = true;
   }
}, true);

window.onbeforeunload = function(e) {
    if(link_was_clicked) {
        return;
    }
    return confirm('Are you sure?');
}

Solution 4 - Javascript

As indicated here https://stackoverflow.com/a/1632004/330867, you can implement it by "filtering" what is originating the exit of this page.

As mentionned in the comments, here's a new version of the code in the other question, which also include the ajax request you make in your question :

var canExit = true;

// For every function that will call an ajax query, you need to set the var "canExit" to false, then set it to false once the ajax is finished.

function checkCart() {
  canExit = false;
  $.ajax({
    url : 'index.php?route=module/cart/check',
    type : 'POST',
    dataType : 'json',
    success : function (result) {
       if (result) {
        canExit = true;
       }
    }
  })
}

$(document).on('click', 'a', function() {canExit = true;}); // can exit if it's a link
$(window).on('beforeunload', function() {
    if (canExit) return null; // null will allow exit without a question
    // Else, just return the message you want to display
    return "Do you really want to close?";
});

Important: You shouldn't have a global variable defined (here canExit), this is here for simpler version.

Note that you can't override completely the confirm message (at least in chrome). The message you return will only be prepended to the one given by Chrome. Here's the reason : https://stackoverflow.com/questions/276660/how-can-i-override-the-onbeforeunload-dialog-and-replace-it-with-my-own

Solution 5 - Javascript

Try this, loading data via ajax and displaying through return statement.

<script type="text/javascript">
function closeWindow(){
	
	var Data = $.ajax({
		type : "POST",
		url : "file.txt",  //loading a simple text file for sample.
		cache : false,
		global : false,
		async : false,
		success : function(data) {
			return data;
		}

	}).responseText;
	
	
    return "Are you sure you want to leave the page? You still have "+Data+" items in your shopping cart";
}

window.onbeforeunload = closeWindow;
</script>

Solution 6 - Javascript

You can try 'onbeforeunload' event.

Also take a look at this-

https://stackoverflow.com/questions/6063522/jquery-beforeunload

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
QuestionCrisView Question on Stackoverflow
Solution 1 - JavascriptHuman BeingView Answer on Stackoverflow
Solution 2 - JavascriptPadmanathan JView Answer on Stackoverflow
Solution 3 - JavascriptAndy MerhautView Answer on Stackoverflow
Solution 4 - JavascriptCyril N.View Answer on Stackoverflow
Solution 5 - JavascriptradunsView Answer on Stackoverflow
Solution 6 - JavascripthalkujabraView Answer on Stackoverflow