Home > other >  How to check if we can go back in JS?
How to check if we can go back in JS?

Time:11-03

I have created a directive in Angular that can go back if there is a history or go to a default route. We can not test in JS if there is previous history. So I make a redirection to the default route and call the history.back() function.

  • Case 1 : there is not history, the history.back() function does nothing and the redirection to the default route is done.

  • Case 2 : there is a history, the redirection to the default route starts but is canceled by the history.back() and the user is redirected to the previous page.

goBack() {      
        if(this.routerCommand) {
            this.router.navigate(this.routerCommand);
        }
        window.history.back();
    }

It works in all browsers except Safari. I don't understand why ?

If someone can help me. Thank's in advance.

CodePudding user response:

Instead using window.history try to use Location. In your.component.ts:

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

constructor(private location: Location) {}

goBack() {      
    if(this.routerCommand) {
        this.router.navigate(this.routerCommand);
    }
    this.location.back();
}

Note: it is important to import Location form @angular/common

CodePudding user response:

First of all, Your code will only got 1 case. The case is: if routerCommand do router.navigate and then whatever is going on do window.history.back();

Next, You can check tab's history by command History.length (ref: https://developer.mozilla.org/en-US/docs/Web/API/History/length)

Answer: I'm not absolutely know the answer. But if you curious about browser compatibility of any feature you can check on this site : https://developer.mozilla.org/en-US/docs/Web/API/History/back#browser_compatibility

  • Related