'Detect url changes in an iframe in an Angular Ionic Mobile App

Problem

I am trying to detect changes to the url of an embedded <iframe /> in an Ionic (v5) app using Angular.

Code

// ts file
  @ViewChild('myIframe') public iFrame;
  backButtonSubscription: Subscription;

  constructor(
    private navCtrl: NavController,
    public platform: Platform,
    private routerOutlet: IonRouterOutlet,
    private router: Router
  ) {}

  ngAfterViewInit() {
    this.backButtonSubscription = this.platform.backButton.subscribeWithPriority(10000, async () => {
      if (this.routerOutlet.canGoBack()) {
        return this.navCtrl.back();
      }

      // Never changes
      const currentRootUrl = this.router.url;

      if (currentRootUrl !== '/my-root') {
        this.navCtrl.navigateRoot('my-root');
      } else if (this.iFrame?.nativeElement?.src === 'https://some-website.com/') {
        App.exitApp();
      } else {
        window.history.back();
      }
    });
  }

// html file
  <iframe id="myIframe" width="100%" src="https://some-website.com/" frameborder="0" #myIframe></iframe>

Context

The iframe is on the root page of the App and I want to detect changes to the url in order to enable navigation via the back button. If the user is on the root of the iframe, then I want to close the app, otherwise I want to navigate back in the iframe. As the embedded url is on another domain than the app, I can't send messages between them.

Is there any way to detect whether the url changed?



Solution 1:[1]

Scripts on different pages are allowed to access each other if and only if the pages they originate from share the same protocol, port number, and host (also known as the "same-origin policy").

Otherwise you have to update both parent and child windows to use postMessage() mechanism: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 plotnik