4

I'm working with Angular 5 app and I need to know how to get the last URL to place it as a link to my back button. I found this location.back() but what I need the last url as a string. How could I get the string that generates location.back()?

Many Thanks!

AlejoDev
  • 4,345
  • 9
  • 36
  • 67
  • Have you checked this. (https://stackoverflow.com/a/41039092/9775003) – Sanoj_V Jun 16 '18 at 04:17
  • Possible duplicate of [How to determine previous page URL in Angular?](https://stackoverflow.com/questions/41038970/how-to-determine-previous-page-url-in-angular) – manan5439 Jun 16 '18 at 06:36

2 Answers2

12

Angular 6 updated code for getting previous url as string.

import { Component, OnInit } from '@angular/core';
import { Router, RoutesRecognized } from '@angular/router';
import { filter, pairwise } from 'rxjs/operators';


export class AppComponent implements OnInit {

    constructor (
        public router: Router
    ) {
    }

    ngOnInit() {
        this.router.events
            .pipe(filter((e: any) => e instanceof RoutesRecognized),
                pairwise()
            ).subscribe((e: any) => {
                console.log(e[0].urlAfterRedirects); // previous url
            });
    }
Franklin Pious
  • 3,670
  • 3
  • 26
  • 30
  • 2
    This is not working in angular 9, When first time I open my page, it won't return previous url, when second time I open my page, that time it return previous url, can you please give me suggestion for this, I have use same code in ngOnInit – S. Deshmukh May 12 '20 at 06:18
1

In the browser environment, location.back() is wrapper around the window.history object (for a partial path through the source, see here, here, here and here).

The contents within the History object are purposefully not accessible.

From the HTML History interface documention:

The actual entries are not accessible from script.

From MDN the window.history object documentation:

For security reasons the History object doesn't allow the non-privileged code to access the URLs of other pages in the session history, but it does allow it to navigate the session history.


As to an alternate approach, this answer provides a technique for listening for the last 2 NavigationEnd events.

chuckx
  • 6,484
  • 1
  • 22
  • 23