I'm making a mobile app and it has a back button in the navbar of the app. The button is used for navigating one level up in the application. Not all levels of the applications are written in the url, some of them are skipped so i cannot rely on the browser back button because not everything is written in the history. So what i want to do is to prevent the default event that happens when you click the back button (even the url change because i have a function that's manually rewriting the url when you click on some parts of the app) and i want the browser's back button to be tied to my custom function. I'm thinking of adding a false state in the history with history.pushstate so when i'm pressing back i'll be going to the false state, but unfortunately you can't have two states with a same name. Do you guys know any solution for this? Thanks
3 Answers
We want to prevent that users can use the back button when logged off or when the token is not valid anymore.
// Prevent to use the back button.
$scope.$on('$locationChangeStart', function(event) {
if (!$scope.isAuthenticated) {
event.preventDefault();
}
});
Where the if is you can implement your url rewrite function. Hope this helps
1 Comment
Kitze
This works for catching the back button but now i cannot set my location manually with $location.path('my/location').
The following code should do the trick:
var allowNav = false;
var checkNav = false;
$rootScope.$on('$stateChangeSuccess', function (event, toState, toStateParams, fromState, fromStateParams) {
allowNav = checkNav;
checkNav = true;
});
$rootScope.$on('$locationChangeStart', function (event, next, current) {
// Prevent the browser default action (Going back)
if (checkNav) {
if (!allowNav) {
event.preventDefault();
}
else {
allowNav = false;
}
}
});
$location.searchproperly throughout your application, so the back button always works as the user expects it to. Changing default/expected functionality never goes down well with end users.$window.history.back();) and have your app properly deep-linked. Your back buttons are under your control. Browser back is not.