angularjspushstate

history.pushState on sub pages in an Angular.js application


I have a blank Angular.js 6 application that uses PathLocationStrategy for routing, and when on a subroute (e.g. /test) and executing the following:

history.pushState({}, '', '#abc');
window.dispatchEvent(new HashChangeEvent('hashchange'));

I would expect the URL to be changed to /test#abc but instead changes the page and URL to the home page (/#abc).

This can be fixed by pretending with the base URL, for example:

history.pushState({}, '', (new URL(window.location.href)).pathname + '#abc');

Unfortunately, I don't have control over the history.pushState command in this case as it's executed externally from ads.

I also tried this in a new Angular 15 application, where similarly the URL updates to /#abc instead of /test#abc but the page didn't change. However, in for example a new Nuxt.js app, it behaves as expected and stays on the test page and the URL becomes /test#abc. So it seems to be perhaps related to Angular.js.

Does anyone know how I can configure my Angular application so it stays on sub-pages when executing:

history.pushState({}, '', '#abc');
window.dispatchEvent(new HashChangeEvent('hashchange'));

Thanks!


Solution

  • Fixed it by doing the following: