0

Using canDeactivate guard I am trying to prevent the browser back action.So, now loading the site url on my browser new tab successfully lands me on the initial page. Now without any user interaction on the page pressing the browser back button takes me back to new tab/blank page state without going into the guard code at all. But if I click anywhere/ scroll within the application before pressing the back button the guard is getting triggered just fine. How can i make the guard run without user interaction on the initial page or trigger user interaction through code?

Within the landing component I have tried creating a hidden element and tried to focus inside onInit which didn't work out.

I am doing lazy loading of the modules inside app-routing.module.ts

const routes: Routes = [
{
   path: '',
   children: [
   { path: '', redirectTo: '', pathMatch: 'full' },
   { path: 'dashboards',
      loadChildren: './dashboards/dashboards.module#DashboardsModule',
      canLoad: [GoBackGuard],
      canDeactivate: [GoBackGuard]
   }]}];

Also did try javascript code to prevent browser back navigation but didnt help as well.

<script>
$(window).load(function(e){
   window.history.pushState(null, "", window.location.href);
window.onpopstate = function() {
   window.history.pushState(null, "", window.location.href);
}
});
</script>
Geo j
  • 181
  • 3
  • 16

1 Answers1

0

Add the following to your app.component.ts constructor:

history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
  history.pushState(null, null, document.URL);
});

This will prevent the browser back button. If you click back, it won't take you back to new tab or previous tab.

Maihan Nijat
  • 9,054
  • 11
  • 62
  • 110
  • Thanks. But its still not working. Only if i scroll or touch somewhere in the page and then click on browser back its actually triggering the event otherwise its not – Geo j Aug 30 '19 at 10:06