Thursday, 4 February 2021

Angular capture brwoser back button and set redirect to another URL && window popstate event in browser

 

Window: popstate event

BubblesNo
CancelableNo
InterfacePopStateEvent
Event handler propertyonpopstate
https://developer.mozilla.org/en-US/docs/Web/API/Window/popstate_event

This event captures browser back or forward button action


Angular capture this browser back button event, and set redirect to different url:

Try this one. Import HostListener

import { Component, HostListener } from '@angular/core';

And then bind event

@HostListener('window:popstate', ['$event'])
onBrowserBackBtnClose(event: Event) {
    console.log('back button pressed');
    event.preventDefault(); 
    this.router.navigate(['/home'],  {replaceUrl:true});
}

https://stackoverflow.com/questions/58185653/change-route-using-browser-back-button-in-angular-6

If want to reload compnent of this redirected new URL :
@HostListener('window:popstate', ['$event'])
onBrowserBackBtnClose(event: Event) {
    console.log('back button pressed');
    event.preventDefault(); 
    this.router.navigate(['/home'],  {replaceUrl:true});

   setTimeout(
    () => {
location.reload();
}
    )
}


Second way:
constructor(router: Router) {
    router.events
      .subscribe((event: NavigationStart) => {
        if (event.navigationTrigger === 'popstate') {
          // Perform actions
        }
      });
}

https://stackoverflow.com/questions/39132737/angular-2-how-to-detect-back-button-press-using-router-and-location-go



No comments:

Post a Comment