是否可以检测到用户通过使用浏览器中的历史记录后退按钮进入页面?我最好使用angular.js来检测这个动作。
我不想使用角度布线。如果用户提交表单,并且在成功提交到服务器并重定向之后,它也应该可以工作,如果用户使用浏览器的后退按钮返回到表单,它也应该是可能的。
发布于 2013-04-05 00:22:12
这是一个使用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?');
}
});
});
我正在使用run块来启动它。首先,我将实际位置存储在$rootScope.actualLocation中,然后侦听$locationChangeSuccess,当发生这种情况时,我用新值更新actualLocation。
在$rootScope中,我观察位置路径的变化,如果新位置等于previousLocation,是因为$locationChangeSuccess没有触发,这意味着用户已经重新使用了历史记录。
发布于 2013-11-18 09:00:46
如果您想要更精确的解决方案(检测后退和转发),我扩展了Bertrand提供的解决方案
$rootScope.$on('$locationChangeSuccess', function() {
$rootScope.actualLocation = $location.path();
});
$rootScope.$watch(function () {return $location.path()}, function (newLocation, oldLocation) {
//true only for onPopState
if($rootScope.actualLocation === newLocation) {
var back,
historyState = $window.history.state;
back = !!(historyState && historyState.position <= $rootScope.stackPosition);
if (back) {
//back button
$rootScope.stackPosition--;
} else {
//forward button
$rootScope.stackPosition++;
}
} else {
//normal-way change of page (via link click)
if ($route.current) {
$window.history.replaceState({
position: $rootScope.stackPosition
});
$rootScope.stackPosition++;
}
}
});
发布于 2016-06-17 18:50:44
对于ui-routing,我使用以下代码。
在App.run()
中,使用
$rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams)
{
if (toState.name === $rootScope.previousState )
{
// u can any 1 or all of below 3 statements
event.preventDefault(); // to Disable the event
$state.go('someDefaultState'); //As some popular banking sites are using
alert("Back button Clicked");
}
else
$rootScope.previousState= fromState.name;
});
你也可以在'$stateChangeSuccess‘事件中获得'previousState’的值,如果你想要的话,如下所示。
$rootScope.$on("$stateChangeSuccess", function (event, toState, toParams, fromState, fromParams)
{
$rootScope.previousStatus = fromState.name;
});
https://stackoverflow.com/questions/15813850
复制相似问题