Michael
Michael

Reputation: 16122

Browser back-button does't work correctly after window.location.href was changed

Before my application was written in jQuery and wasn't SPA. I have rewritten some of the pages to AngularJS and made them SPA.

Now I need to have proper comunication beetwen these apps. Because when I go from Angular page to Angular page, I don't want to reload the page, but when I go to jQuery page, I do want to reload the page so server could send me other source files.
So, when the link goes to the Angular page (from Angular page), it's simple:

<a href="store/categories">

And ui-router catches "store/categories", changes the state and it doesn't reload the page.

However if the link goes to jQuery page (from Angular page), I can't just specify <a href="store/categories">, because ui-router will catch it and the page won't reload.

Then I decided to use window.location.href to force page reload:

<a href="store/categories" ng-click="$root.newHref('store/categories')">

$rootScope.newHref = function(url) {
   var url = ROOT_URL + urlBody; // ROOT_URL is just a protocol with host name
   window.location.href = url;
};

And it worked! When you now click on the link it will reload the page with the correct URL.

However if you go to a page using window.location.href and then click the browser back button, the URL will change but the page won't reload.

How can I fix it?

Upvotes: 2

Views: 2383

Answers (2)

Sander Ravenhorst
Sander Ravenhorst

Reputation: 169

I had this exact same problem going back and forward between 2 apps.

As the old app didn't use HTML5 History API functionality, i fixed this by added this piece of javascript in the old website pages (in a JavaScript file that was loaded by all pages in the old website:

//This will fix a bug with browsers history back API after a window.location from within our Angular apps.
(function () {
  var locationOnPageload = location.href;
  window.onpopstate = function (event) {
    if (location.href !== locationOnPageload) {
      document.location.reload();
    }
  }
})();

As Safari on mobile was triggering "onpopstate" on page load, I added the check if href on page-load is different then location onpopstate.

This way I don't have to add target="_self" to all links that go back to our old style pages.

Upvotes: 0

Michael
Michael

Reputation: 16122

Use target="_self" instead of window.location.href.

Upvotes: 2

Related Questions