I have a handler for onbeforeunload
window.onbeforeunload = unloadMess;
function unloadMess(){
var conf = confirm(\"Wait! Before you go, please share your
There is a good solution to this which I implemented in my website recently. Just imagine this, everything thats going to be in your website that navigates the user is either going to be a link (anchor tag), button, clickable image or something on these lines. Its definitely not going to be the body element.
Now what happens when a user leaves the website, he/she can either type in a url and press enter, click a bookmark or press the back/forward buttons.
When a user does do that, do this:
$(window).on('beforeunload', function(e)){
if(e.target.activeElement.nodeName.toLowerCase() == 'body'){
yourFunction();
});
What happens is that the body becomes the active element in the target in these cases (when user leaves the website) and this is not the case when the user clicks on internal website navigable elements.
This is a clean, easy solution. Let me know if you face any issues.