Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect browser back button click event using angular?

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.

like image 492
Thomas Kremmel Avatar asked Apr 04 '13 14:04

Thomas Kremmel


People also ask

What is the event for browser back button?

Normally, the onbeforeunload event is used for handling browser back button functionality as follows: <body onbeforeunload="HandleBackFunctionality()"> function HandleBackFunctionality()

What event is fired when the back button of a browser is pressed?

The popstate event is fired each time when the current history entry changes (user navigates to a new state). That happens when user clicks on browser's Back/Forward buttons or when history. back() , history.

What is NavigationStart in angular?

The Angular Routers triggers several events starting with when the Navigation starts ( NavigationStart ) and also when the Navigation end ( NavigationEnd ) successfully. It is triggered when the navigation is canceled either by the user ( NavigationCancel ) or due to an error in the navigation ( NavigationError).


1 Answers

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.

like image 132
Bertrand Avatar answered Sep 17 '22 20:09

Bertrand