Event.preventDefault () with Angularjs and UIRouter deletes browser history

I show a Javascript Confirm prompt when users click the browser Back button while watching the $stateChangeStart event. Consider the following:

Users move from page 1, 2, and then to page 3. On page 3, the user presses the Back button, they are presented with a confirmation window. The user clicks the Cancel button, event.preventDefault() is executed, and the user remains on the same page. Then, if the user presses Back again and selects OK a second time, the user returns to page 1. What happened to page 2? Does event.preventDefault() latest story? How to prevent browser from switching to the previous page?

 $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) { var retVal = confirm("You have unsaved changes. If you leave the page, these changes will be lost."); if (retVal == false) { // user wants to cancel navigating back. event.preventDefault(); } }); 
+5
source share
1 answer

If you want to save the history without allowing the back button to be pressed, you need to do this by observing $ locationChangeStart , not $ stateChangeStart .

This is due to the fact that $ stateChangeStart, unlike $ locationChangeStart, is widespread after the transition has been completed and the browser history has already been updated.

So it should look like this:

 $rootScope.$on('$locationChangeStart', function(event, next) { var retVal = confirm("You have unsaved changes. If you leave the page, these changes will be lost."); if (retVal == false) { // user wants to cancel navigating back. event.preventDefault(); } }); 
0
source

Source: https://habr.com/ru/post/1243324/


All Articles