简体   繁体   中英

Listening to URL changes of an angular application

I have an application which contains an iframe , the iframe is rendering an angular 4 application. I tried to listen to the iframe 's URL in the following way:

frame.src = appSource;
    frame.addEventListener('load', function () {
        frame.contentWindow.window.sdk = frame.contentWindow.window.sdk || sdk;
        frame.contentWindow.window.addEventListener('hashchange', () => console.log('url changed!!!'), true);
    }, true);

Unfortunately, I couldn't see the console.log message. The angular application (which is inside the iframe ) is using the angular router to navigate between pages, using a code like this:

this.router.navigate(['/page']);

Moreover, the angular application uses useHash: true in its RouterModule :

RouterModule.forRoot(ROUTES, {useHash: true, preloadingStrategy: AppCustomPreloader })

I tried to replace it with useHash: false and change the event listener to onpushstate , but unfortunately, it didn't work.

Any idea how can I listen to the URL changes of the angular app?

Look into Angular navigation events: https://angular.io/guide/router#router-events

Eg. you could call window.postMessage on NavigationEnd in Angular and listen to that in the parent frame. https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

Ie. there's no way to detect a hash change or a history push from outside the frame but postMessage is a safe way to communicate between frames.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM