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.

4
  • 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) Commented Sep 24, 2015 at 9:31
  • possible duplicate of Control or Disable Browser Back Button with Javascript or AngularJS Commented Sep 24, 2015 at 9: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. Commented Sep 24, 2015 at 9: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. Commented Sep 24, 2015 at 9:54

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.