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

前端 未结 5 2018
攒了一身酷
攒了一身酷 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条回答
  •  感动是毒
    2020-12-29 10:53

    It's not possible to do this 100% reliably, but if you detect when the user has clicked on a link on your page, you could use that as a mostly-correct signal. Something like this:

    window.localLinkClicked = false;
    
    $("a").live("click", function() {
        var url = $(this).attr("href");
    
        // check if the link is relative or to your domain
        if (! /^https?:\/\/./.test(url) || /https?:\/\/yourdomain\.com/.test(url)) {
            window.localLinkClicked = true;
        }
    });
    
    window.onbeforeunload = function() {
        if (window.localLinkClicked) {
            // do stuff
        } else {
            // don't
        }
    }
    

提交回复
热议问题