Fire onbeforeunload confirm alert for external sites only

前端 未结 1 1393
-上瘾入骨i
-上瘾入骨i 2021-01-25 03:49

I am using window.onbeforeunload method to show confirm message if user leaves website.

window.onbeforeunload = function(e) {
    return textMsg;
};


        
相关标签:
1条回答
  • 2021-01-25 04:21

    Try (untested code):

    window.onbeforeunload = function(e) {
        return textMsg;
    };
    
    $('a:not([href^="http"])').on('click', function() {
        window.onbeforeunload = null; // prevent message
    });
    
    $('form').on('submit', function() {
        window.onbeforeunload = null; // prevent message
    });
    

    This will prevent the event from triggering if links do not start with http (external links) and for <form> submits. Looking for a solution for window closing at the moment.

    0 讨论(0)
提交回复
热议问题