Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
87
rated 0 times [  94] [ 7]  / answers: 1 / hits: 95327  / 11 Years ago, thu, april 4, 2013, 12:00:00

Is it possible to detect that a user entered a page through using the history back button in his browser? Preferably I want to detect this action using angular.js.



I do not want to use angular routing. It should also work if a user submits a form and after a successful submit to the server and a re-direct, it should also be possible if the user goes back to the form using the back button of the browser.


More From » jquery

 Answers
9

Here is a solution with Angular.



myApp.run(function($rootScope, $route, $location){
//Bind the `$locationChangeSuccess` event on the rootScope, so that we dont need to
//bind in induvidual controllers.

$rootScope.$on('$locationChangeSuccess', function() {
$rootScope.actualLocation = $location.path();
});

$rootScope.$watch(function () {return $location.path()}, function (newLocation, oldLocation) {
if($rootScope.actualLocation === newLocation) {
alert('Why did you use history back?');
}
});
});


I am using a run block to kickstart this. First I store the actual location in $rootScope.actualLocation, then I listen to $locationChangeSuccess and when it happens I update actualLocation with the new value.



In the $rootScope I watch for changes in the location path and if the new location is equal to previousLocation is because the $locationChangeSuccess was not fired, meaning the user has used the history back.


[#79119] Wednesday, April 3, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
trayvon

Total Points: 35
Total Questions: 117
Total Answers: 88

Location: Guernsey
Member since Tue, Jul 6, 2021
3 Years ago
;