0

I am working on a SPA using AngularJS. I want to navigate through application states using links in application and I want to prevent the same navigation when back button is clicked.

All the solutions I found including $locationChangeStart in angularJs prevent navigation when I click links in my app also.

Please provide a solution which prevents only browser back button navigation and allows navigation through clicking link in application.

Madhura KM
  • 140
  • 1
  • 10
  • This is technically not possible (changing Browser behaviour via javascript), because it would be a massive security-problem for users. You need to work around this problem. I mostly see iFrame capturing for this need (basically wrapping your content in an iFrame makes the back Button of the Brwoser useless for the parent site) – mondjunge Sep 24 '15 at 09:31
  • possible duplicate of [Control or Disable Browser Back Button with Javascript or AngularJS](http://stackoverflow.com/questions/29345481/control-or-disable-browser-back-button-with-javascript-or-angularjs) – SANN3 Sep 24 '15 at 09:39
  • @SANN3, I have tried this solution. it prevents navigation by clicking links in app also along with browser back button. Hence not a solution for my problem. – Madhura KM Sep 24 '15 at 09:42
  • The preventDefault prevents any bevaviour that angular would normally do. You have to figure out a mehtod to filter out links that are valid for the current application state and do preventDefault conditionally. There's no magical way around that, i fear. – Kevin Dreßler Sep 24 '15 at 09:54

1 Answers1

1

The easiest way to do this would be to have a mapping of transitions from current application state (url) to valid next application states (urls) and only preventDefault iff the transition from the current state to the one desired by $locationChangeStart isn't valid.

If you go about it like this, you not only prevent the user from using the back button but also from putting undesireable urls in the browser to create invalid application state and possibly harm your application.

I suggest you don't use some "on history change history.forward" method like linked in the other answer, it's the worst UX possible, make it transparent to the user.

Kevin Dreßler
  • 447
  • 2
  • 15