Detect hashchange when the Angular SPA routes to different state.
Detailed information on the approach and the solution in my blog: https://www.moritz-benzenhoefer.com/2019/03/angular-detect-hashchange-from-outside/.
Listening to the hash change of the browsers' URL is a big deal when not using HTML5 location API. Since Angular uses the history
API (because of states etc.), there is no other option to use when working with Angular and listening to the URL hashchange
from outside the application (p.e. when running in a frame and propagate the change to the parent).
My solution overwrites the default HashLocationStrategy
of Angular. It calls the HashLocationStrategy
s method to route in the application and then throws the hashchange
event manually.
Use the location strategy provided by this library instead of Angulars' HashLocationStrategy.
First you need to install the npm module:
npm install ngx-hashchange-location-strategy
// ...
import { HashChangeCompatibleHashLocationStrategy } from 'ngx-hashchange-location-strategy';
@NgModule({
// ...
providers: [
{ provide: LocationStrategy, useClass: HashChangeLocationStrategy },
// ...
],
// ...
})
export class AppModule {}
The event payload contains the properties oldURL
and newURL
as the standard HashChangeEvent does.
const handleHashChange = evt => {
console.log('hashchange event triggered!');
console.log(evt);
};
window.addEventListener('hashchange', handleHashChange);
Due to the fact that there may be multiple routings ongoing (one after an other) in the same Angular cycle, only the last hashchange
event is propagated. Reason: Angular listens to HashChangeEvents
and if we throw it again and again, the application will stuck in an infinite routing loop.