Display a warning when leaving the site, not just the page

前端 未结 7 825
旧时难觅i
旧时难觅i 2020-12-05 20:55

This sounded like something almost impossible to do when it was presented to me. I know you can display a dialog box to confirm when leaving a web page. But is it possible t

7条回答
  •  一整个雨季
    2020-12-05 21:26

    Using the expression from this question, you can do the following:

    $.expr[':'].external = function(obj){
        return !obj.href.match(/^mailto\:/) && (obj.hostname != location.hostname);
    };
    $.expr[':'].internal = function(obj){
        return obj.hostname == location.hostname;
    };
    
    $(function() {
        var unloadMessage = function() {
            return "Don't leave me!";
        };
    
        $('a:internal').click(function() { 
            window.onbeforeunload = null;
        });
        $('form').submit(function() { 
            window.onbeforeunload = null;
        });
    
        $('a:external').click(function() { 
            window.onbeforeunload = unloadMessage;
        });
    
        window.onbeforeunload = unloadMessage;
    });
    

提交回复
热议问题