1

I am trying to redirect the user to a particular url on the click of back button in browser, and here is the code

constructor(private router: Router,private location: PlatformLocation) {        
        let eventUrl = window.sessionStorage.getItem('Event');
        this.location.onPopState(() => {
            alert('click');
            this.router.navigate(['/', this.selectedLanguage, 'event', eventUrl]);
        });
    }

but it does not seem to fire the event when user click on back button. The code is in the current component. what is the issue?

EDIT

I tried with the below answer suggested, but that too does not seems to work, the function getting called , but it still redirects to the previous page rather than the mentioned url below

unload(event: any) {
        let eventUrl = window.sessionStorage.getItem('buyerEvent');
        this.router.navigateByUrl('/' + this.selectedLanguage + '/event/' + eventUrl);
    }
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396

2 Answers2

3

You can bind things you want to do while leaving the app to window.unload event. Here I used the HostListener.

@HostListener('window: unload', ['$event'])
unload(event) {
  window.open('https://localhost:4200', '_blank');
  window.close();
}

Mention that Chrome will block window.open by default, you have to change block policy.

Pengyy
  • 37,383
  • 15
  • 83
  • 73
  • @Sajeetharan I just confirmed at my local app and it's working fine. BTW, I test by locating above code at `AppComponent`, but this shouldn't matter I think. – Pengyy Aug 15 '17 at 10:23
  • the function is getting invoked , but it does not redirect to a different url. it goes back to the stripe window which was the previous one in this case – Sajeetharan Aug 15 '17 at 16:24
  • @Sajeetharan `window.open` will open the different url in a new tab, and `window.close` will close the current tab. This is for your specific requirement. – Pengyy Aug 16 '17 at 01:01
  • @Sajeetharan Also make sure that you are opening the url in **new tab**, for some reason it won't work when you try to open it in current tab. – Pengyy Aug 16 '17 at 01:08
-1

I'm use Location

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

declare on constructor

constructor(private _location: Location){}

and make a function

backClicked() {
    this._location.back();
}

then set it into button

<button (click)="backClicked()"> TEAM FALL BACK</button>

Then watch the magic happen ...

Nuttertools
  • 120
  • 1
  • 6