I would like to detect when a user is about to exit the page, before they click the back button, and do something - for example display a popup. I do not want to prevent the user from leaving the page, but only to grab their attention again.
This is already done by Optin Monster, but I want to implement it myself.
Where to start?
Edit:
beforeunload
is fired after the user clicked the back or x button. I would like to catch his exit intent, for example when the mouse is moving towards the back button, but before it was clicked.
Ouibounce does this. There is a live demo here.
npm install ouibounce
Then:
var ouibounce = require('ouibounce');
var modal = document.getElementById('ouibounce-modal')
ouibounce(modal);
Here's how you can do it:
$(document).on('mouseleave', leaveFromTop);
function leaveFromTop(e){
if( e.clientY < 0 ) // less than 60px is close enough to the top
alert('y u leave from the top?');
}
I hope this is what you are looking for. Good luck!
The problem I find with these techniques (like the one implemented on Ouibounce or the one proposed by Hristo Georgiev) is they also detect when the mouse enters the window if the cursor is outside the page before page load. It's not a big deal, but it might bring an unwanted behavior. An extra tweak must be done for this solution to work fine. One thing that comes to my mind right know would be to use a flag to check the mouse logic.
来源:https://stackoverflow.com/questions/24016658/how-can-i-detect-a-user-about-the-exit-the-page