How can I detect when the user is leaving my site, not just going to a different page?

前端 未结 5 2013
攒了一身酷
攒了一身酷 2020-12-29 10:08

I have a handler for onbeforeunload

window.onbeforeunload = unloadMess;
function unloadMess(){
  var conf = confirm(\"Wait! Before you go, please share your          


        
5条回答
  •  -上瘾入骨i
    2020-12-29 10:48

    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.

提交回复
热议问题