el.severo el.severo - 4 years ago 2393
Javascript Question

javascript or angularjs defer browser close or tab close between refresh

Is there any way to trigger if the user refreshes the page or closes the browser / browser tab? (I'd like to trigger that in AngularJS / JavaScript). Any thoughts about this?

Right now I know only when the current page closes with the following code:

var myEvent = window.attachEvent || window.addEventListener;
var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, IE8 compatable

myEvent(chkevent, function (e) { // For >=IE7, Chrome, Firefox
var confirmationMessage = ' '; // a space
(e || window.event).returnValue = "Are you sure that you'd like to close the browser?";
return confirmationMessage;
});

Answer Source

Your directive may look like this:

myApp.directive('myDirective', function() {
    return function($window) {
        var myEvent = $window.attachEvent || $window.addEventListener,
            chkevent = $window.attachEvent ? 'onbeforeunload' : 'beforeunload'; 

        myEvent(chkevent, function(e) {
            var confirmationMessage = ' ';
            (e || $window.event).returnValue = "Are you sure that you'd like to close the browser?";
            return confirmationMessage;
        });
    }
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download