Syncing browser back with ionic history

I’m using the same ionic project for the web (mobile/desktop) as well as for a cordova app, which requires some hacking but works quite OK now.

One problem I’m having is that clicking the browser’s back button breaks ionic’s history, which is used by the app internal navigation.
The problem arises when clicking browser’s back after manipulating the history view via ionicHistory, by using for example:
$ionicHistory.nextViewOptions({ //disable back
historyRoot: true,
disableBack: true
});
or
$ionicHistory.currentView($ionicHistory.backView());

Any solution or even idea towards this will be welcome.

I merge the ionic app project to wechat webapp and face with the same problem.

My idea is to keep the brower’s history same as the ionic history, when the browser back button is pressed

$rootScope.$on("$ionicView.beforeEnter",function(a,ready_to_enter){// 

console.log(a);
console.log(ready_to_enter);

var ready_to_enter_state_id = ready_to_enter.stateId;
var ready_to_enter_state_name = ready_to_enter.stateName;
var historyObj = $ionicHistory.viewHistory();
var stack = historyObj.histories.root.stack;

// "forward" may be driven by browser's back button
if ("forward" == ready_to_enter.direction) {
    var count_state_id = 0;
    stack.forEach(function(view) {
        if (view.stateId.indexOf(ready_to_enter_state_id) != -1) {
            count_state_id += 1;
        }
    });
/*
 The number of ready_to_enter_state shall be one. 
 If there are two, the browser back button is pressed.
 */
    if (count_state_id > 1) {
        console.log("invoking browser callback");
        $ionicHistory.nextViewOptions({  disableAnimate: true });
        $ionicHistory.goBack(-2);
        var last = historyObj.histories.root.stack.pop();
        if (!!last) {
            delete historyObj.views[last.viewId];
        }
    }// end // count_state_id>1
}// end if "forward" 

});//end $rootScope.$on

The code above is just a reference and there are some problems considering the difference sequence combined with ionic’s history driven by state.go(…) and the browser’s back button.

Hope anyone can make some further solution.

As I track the source code , the sequence hereunder is found

1.View.prototype.go
2.$state.go
3.$state.transitionTo
4.handleRedirect
5. $urlRouter.update()

The update code is
update: function(read) {
if (read) {
location = $location.url();
return;
}
if ($location.url() === location) return;

    $location.url(location);
    $location.replace();
  },

This code $location.url(location) cause the the problem.

It may means that “append new url to the browser history” not delete “old one” sometimes.

So history.go(-1) instead of the operation of $ionicHistory can solve the problem.