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

前端 未结 5 2014
攒了一身酷
攒了一身酷 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:46

    If you are having issues because your website may have both absolute and relative local links, I have another solution (using jQuery):

    Demo

    /* EXTERNAL LINK WARNING
    =========================================*/
    $('a').on('click', function(e){
        e.preventDefault();
        var url = $(this).attr('href'),
            host = location.host;       
        if (url.indexOf(host) > -1 || url.indexOf('http','https') == -1){
            /* If we find the host name within the URL,
                   OR if we do not find http or https, 
                   meaning it is a relative internal link
                */
            window.location.href = url;
        } else {
            var warn = confirm('You\'re leaving the domain.\n\nAre you sure?');
            if(warn == true) {
                window.location.href = url,'_blank';
            } else {
                e.preventDefault;
            }
        }
    });
    

提交回复
热议问题