open a custom popup on browser window/tab close
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<title>K3logics.com</title>
<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 ++;
}
});
</script>
</head>
<body>
<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="https://www.k3logics.com" target="_blank">https://www.k3logics.com</a></h1>
</div>
</body>
</html>
i would also suggest you dont do this, However, you asked a question and deserve an answer.
UPDATE (2022) This code does not work anymore due to new browser security settings.
var popit = true;
window.onbeforeunload = function() {
if (popit == true) {
popit = false;
return "Are you sure you want to leave?";
}
}
On october 2019 it's possible just in internet explorer https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event
window.onbeforeunload = function (e)
{
e = e || window.event;
e.returnValue = 'You want to leave ? ';
};
jsFiddle