Reputation: 125
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
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
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