0

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

Ash
  • 447
  • 2
  • 6
  • 19
  • 2
    Does this answer your question? [How can I stop the browser back button using JavaScript?](https://stackoverflow.com/questions/12381563/how-can-i-stop-the-browser-back-button-using-javascript) – Shabbir Dhangot Aug 24 '22 at 01:57
  • If you really wish user to redirect to new app then from server configuration you can redirect to new URL permanently 301 so browser will not remember previous URL and no need to disable back button. – Shabbir Dhangot Aug 24 '22 at 02:01
  • @ShabbirDhangot Thank you for your answer, but I still have not found an answer. I tried the javascript from the above link. It only works if the end-user made a state change, otherwise, it doesn't work I get below error from the browser. "Blocked attempt to show a 'beforeunload' confirmation panel for a frame that never had a user gesture since its load" – Ash Aug 29 '22 at 04:23
  • @ShabbirDhangot regarding the redirect, yes I use RedirectPermanent in .Net 4.8 MCV application, however it does 304 redirect instead of 301 – Ash Aug 29 '22 at 04:34
  • You need 301 only to inform browser that it moved permanently. Check with any system admin for same. – Shabbir Dhangot Aug 29 '22 at 05:49
  • See if this help you https://learn.microsoft.com/en-us/dotnet/api/system.web.httpresponse.redirectpermanent?view=netframework-4.8 – Shabbir Dhangot Aug 29 '22 at 06:01

1 Answers1

0

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.

Ash
  • 447
  • 2
  • 6
  • 19