Amichay_Atias
Amichay_Atias

Reputation: 125

How to know if page was closed / refreshed / 'go back' was pressed in angular 2+

I'm trying to use the function window.addEventListener('beforeunload', function (event) {...} In the function, I want to know which action triggered the listener.

I tried to use this method with no success:

window.addEventListener('beforeunload', function (event) {
     if (performance.navigation.type == 1) {
        document.write('Window was refreshed!');
     } 
     else {
        document.write('Window was closed!');
     }
}); 

Any action (refresh/close/'go back') triggers the else part... what am I doing wrong?

Alternative method would be appreciated as well.

Upvotes: 0

Views: 621

Answers (2)

Eliseo
Eliseo

Reputation: 57939

use router events You can subscribe in your app.component like

ngOnInit() {
  this.router.events
    .subscribe((event) => {
      // example: NavigationStart, RoutesRecognized, NavigationEnd
      console.log(event);
    });
}

Upvotes: 0

vicbyte
vicbyte

Reputation: 3790

Well, you always trigger the else handler, because of the way peformance.navigation works. Even if you write it in the beforeunload handler, it still runs on your current document, not the one you are loading, so it will output the PerformanceNavigation object that contains info on how you opened your current page, and not the one you are trying to navigate to.

As to the part in your question about deteciting whatever method user used to leave the page, i don't think thats possible at the moment, not without usage of 'dirty' hacks/workarounds (detecting which button has user clicked, detecting keyboard events, etc.)

Upvotes: 1

Related Questions