<script>
document.addEventListener("mouseout", function (e) {
if (!e.toElement && !e.relatedTarget && e.clientY < 10) {
showExitPopup();
}
});
function showExitPopup() {
alert("Wait! Before you go, check out my latest article."); // Replace this with your popup logic.
}
</script>
This code detects when the user moves the mouse near the top of the page (which often means they're heading to the close tab or back button) and triggers a message.
🚀 Note: Implementing this code significantly improved my Google Analytics 4 reports, especially in cases where user engagement metrics surpassed page views. I was initially frustrated to see repeated traffic from certain countries registering consistent user engagement but showing zero page views. This tweak helped bridge that reporting gap and offered clearer insights into actual user behavior.