Javascript – open a custom popup on browser window/tab close


I am trying to open a custom popup on browser window/tab close.

In details if a user clicks on the browser window/tab close button a custom popup will appear with some content or may be having some option asking to close or continue the page.

here is the code which only bring the default alert popup:

window.onbeforeunload = function() {
              var message = 'Do you want to leave this page?';
              return message;

Best Solution

<!DOCTYPE html>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<script src=""></script>
		var mouseX = 0;
		var mouseY = 0;
		var popupCounter = 0;

		document.addEventListener("mousemove", function(e) {
			mouseX = e.clientX;
			mouseY = e.clientY;
			document.getElementById("coordinates").innerHTML = "<br />X: " + e.clientX + "px<br />Y: " + e.clientY + "px";

		$(document).mouseleave(function () {
			if (mouseY < 100) {
				if (popupCounter < 1) {
					alert("Please do not close the tab!");
				popupCounter ++;

	<div id="page-wrap">
		<span id="coordinates"></span>	
		<h1>Hi, Move your mouse cursor around then try to close the window of browser! - <a href="" target="_blank"></a></h1>