ScubaSteve
ScubaSteve

Reputation: 8270

CanDeactivate Not Firing in iFrame

I have an application which has an iframe into a separate Angular application. The src of the iframe is to a component. Long story short, the Angular app has to redirect to the home page, then back to the component in the src. If I use my back button on my mouse while the cursor is in the iframe, the Angular app goes back to the home page (since it redirected from there). So, to prevent this, I put this guard on the component's route.

@Injectable({
  providedIn: 'root',
})
export class CannotDeactivateGuard implements CanDeactivate<unknown> {
  canDeactivate(
    component: unknown,
    currentRoute: ActivatedRouteSnapshot,
    currentState: RouterStateSnapshot,
    nextState?: RouterStateSnapshot
  ):
    | Observable<boolean | UrlTree>
    | Promise<boolean | UrlTree>
    | boolean
    | UrlTree {
    // Always returns false as we do not want the user to navigate away.
    // Example use is if a component is used in an iframe. We do not want the user to be able to navigate within the iframe.
    console.log('RETURN FALSE FROM CANNOT DEACTIVATEGUARD');
    return false;
  }
}

The console is not logging the message and the application is still going back to the home page.

UPDATE

I noticed even when hitting the component directly on its own page (not in an iframe) the CannotDeactivateGuard is not firing when the back button is clicked.

Upvotes: 0

Views: 203

Answers (1)

ScubaSteve
ScubaSteve

Reputation: 8270

A work-around that I found was to call this code in the component's ngOnInit().

constructor(protected locationStrategy: LocationStrategy) {}

ngOnInit(): void {
  history.pushState(null, null, location.href);
  this.locationStrategy.onPopState(() => {
    history.pushState(null, null, location.href);
  });
}

It isn't great. I wish Angular's CanDeactivate when implemented took care of this. The more I use it, the more I'm disappointed with it.

Upvotes: 1

Related Questions