Search code examples
javascriptangularjsonbeforeunload

Fire onbeforeunload confirm alert for external sites only


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

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

But I need this to be fired only if user navigates to external web-site or closes window.

So how to cancel this confirm message for all XHR inside same domain and form submit etc?


Solution

  • 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.