0

My main issue is the following. I'm redirecting a page using the router in an AngularJS application to a Angular application. This works fine but when trying to go back to the page you came from you'll have to click the back button twice because when on a page going to a route, you load to route itself and then you redirect.

Example: you're on page A (AngularJS), you go to page B (AngularJS route) which redirects to C (Angular application).

When on page C you use the back button and as a user you expect to go back to page A but instead you go to page B and are redirected again to C.

Right now I think about detecting if the back button was clicked and the going back in the history with

window.history.go(-2)

Going back in the history works and I found a lot of questions and answers on SO to detect clicking the back button. But these ways of detecting the back button do not work when your origin is an AngularJS application and your code is in your Angular application.

Any idea how to detect the back button when your previous page was not the same application?

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Nicholas
  • 1,189
  • 4
  • 20
  • 40
  • Can’t you just replace your redirect from B to C with this method? https://stackoverflow.com/questions/19012915/angularjs-redirect-without-pushing-a-history-state – CBroe Mar 08 '18 at 15:18
  • I don't think that's possible, it seems the only way to go outside your application is using window.location.href – Nicholas Mar 08 '18 at 15:58

1 Answers1

0

For now I came up with this solution.

In the routing of my AngularJS app I used:

        redirectTo: function(routeParams) {
            window.location = 'http://externalpathtoAngularApp';
        }

and then in the Angular app in the controller of the page that is redirected to I added the following to the constructor of my class

if (document.referrer === 'http://originOfAngularJSApp') {
  window.onpopstate = function () {
    console.log(document.referrer);
  };
  history.pushState({}, '');
}

and also add this HostListener in the class after the constructor

  @HostListener('window:popstate', ['$event'])
  onPopState(event) {
      if (document.referrer === 'http://originOfAngularJSApp') {
        window.history.go(-2);
      }
  }

This is somewhat satisfying but it doesn't cover all the scenario's yet. For example if you come from app A and are redirected to C, then it goes back to A is expected.

But if you come from A redirected to C and then go to D, F... (in the Angular app) and then go back to C using the back button and finally using the back button to go to A you will be redirected to C again.

So in this case it's not completely covered yet.

Nicholas
  • 1,189
  • 4
  • 20
  • 40