Search code examples
javascriptangularfrontendweb-deploymentangular12

Disable Browser Back Button in Angular 12


I am developing a SPA using Angular 12.

Users do not directly load this web application, they open another web application first and then redirect to the new SPA.

In the new SPA, I want to disable the browser back button to stop navigating away. New SPA has all the control if the user really wants to go back.

I have used the below code to disable the back button and but it doesn't work on the initial page that the user gets after the first redirection. From there onwards, the back button is disabled.

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
  ngOnInit(): void {
    history.pushState(null, '');
  }
}

Because of the redirection browser knows the previous place and allows to go back.

Do you know how can I fix this issue?

Thanks and regards,

Ash


Solution

  • This is a chrome behavior that we cannot disable the back button if the user has not done any interaction with the page.

    Getting this working from chrome

    [Intervention] Blocked attempt to show a 'beforeunload' confirmation panel for a frame that never had a user gesture since its load.