Angular: Location back history

Cequiel picture Cequiel · Jan 23, 2018 · Viewed 23.8k times · Source

I have a form with a "back" button. When the user presses the back button, the script goes to the previous page:

import { Location } from '@angular/common';

// In a place in La Mancha, whose name I do not want to remember...
this.location.back();

But, what happens when the user directly enters the url in the address bar? In those cases the application goes back to the Browser's homepage. I would like something like this:

import { Location } from '@angular/common';

// In a place in La Mancha, whose name I do not want to remember...
if (this.location.history.length > 0) {
    this.location.back();
} else {
    this.router.navigate(['/home');
}

Is that possible?

Answer

paragonid picture paragonid · Feb 13, 2018

You could check the history with window.history.length. Therefore your function would look like

goBack() {
  if (window.history.length > 1) {
    this.location.back()
  } else {
    this.router.navigate(['/home'])
  }
}

docs: https://developer.mozilla.org/en-US/docs/Web/API/Window/history

The problem with it is that some browsers (e.g. chrome) store initial page in the history, so window.history.length > 1 and you will be sent to browser's initial page.

In my application I had to implement additional logic to determine where should user go in similar case.

goBack() {
  if (this.isHistory) {
    this.router.navigate(['/history'])
  } else {
    this.router.navigate(['/home'])
  }
}

Here's details on how to determine what was your previous URL: How to determine previous page URL in Angular?