5

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.

3 Answers3

7

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.

Koen Morren
  • 1,233
  • 2
  • 9
  • 12
4

This one worked for me, but you need to pay attention that the custom message doesn't work in most of the browsers, (such as chrome, IE, firefox).

window.onbeforeunload = () => {
     return 'Are you sure you want to leave without saving?';
}

This will fired when the user refresh or close the tab or window, with the browser default message.

Galdil
  • 499
  • 5
  • 11
-1

i have tried this code, it works for me!

      window.onbeforeunload = close;
                function close(){

                    // do something...
                    localStorage.clear();
                    sessionStorage.clear();
                   return null;
                }
Python Basketball
  • 2,320
  • 3
  • 24
  • 47