Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Fire Angularjs Event when close browser or window?

I want to clear local storage values when user close browser or window tab using in angularjs. I tried the following code.

window.addEventListener("beforeunload", function (e) {
        var confirmationMessage = "\o/";
        alert("exit");
        (e || window.event).returnValue = confirmationMessage; //Gecko + IE
        return confirmationMessage;                            //Webkit, Safari, Chrome
    });

In the above code it asks the confirmation alert messages when refresh the page and also close the page. But i want to fire angularjs event when close the browser/Window Tab only no need to ask the confirmation messages.

like image 822
durga siva kishore mopuru Avatar asked Feb 09 '23 00:02

durga siva kishore mopuru


1 Answers

In the last project I worked on, I used the following code:

$window.onbeforeunload = function (event) {
    if (self.form.$dirty) {
        return 'You have made changes, but you did not save them yet.\nLeaving the page will revert all changes.';
    }
}

First it performs a check to see if the data in the form has been changed. If so, when the user tries to close the window or go to another url, a popup will be shown stating that there are unsaved changes.

So in this event you have access to the controller, so all angular events should be able to fire.

like image 174
Koen Morren Avatar answered Feb 11 '23 01:02

Koen Morren