Angular2 Check if Location.back has history to go back?
You can use JavaScript to view the last place the user visited:
document.referrer
doc
So, in your case, you can check if the user can go back, as follows:
historyBack() {
if (document.referrer) {
this._location.back();
}
}
In Angular 7
you can use Router.navigated
property to check if any navigation event has occurred.
constructor(
private router: Router,
private location: Location
) {
this.hasHistory = this.router.navigated;
}
Tried many solutions out there-
this.router.navigated
always returnedtrue
for some reason (maybe because I'm navigating to another page viaredirectTo
in routing).- I tried with
history.length
but that always returned 2. - Then tried to use
history.state
to check if doesn't contain any arbitrary data, then I can assume it's a fresh tab open without any history. But it was only setting{navigationId: 1}
(by Angular) so was not useful when refreshing an existing tab with existing history.
Finally, I thought of using sessionStorage
this way which is working fine for me.
In a global space (let's say in app.component.ts
), I did this-
ngOnInit(): void {
this.router.events.pipe(
filter(event => event instanceof NavigationEnd),
).subscribe(() => {
let navigations = parseInt(sessionStorage.getItem('totalNavigations'), 10) || 0;
navigations++;
sessionStorage.setItem('totalNavigations', navigations.toString());
});
}
Now, when I want to go back to see if there is any history, I'm doing this-
goBack(): void {
const totalNavigations = parseInt(sessionStorage.getItem('totalNavigations'), 10);
if (totalNavigations > 1) {
this.location.back(); // Or history.back()
} else {
this.router.navigateByUrl('/my-default-path')
}
}