Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subscribe to src Change of Iframe in Angular 7

Tags:

angular

iframe

We are Looking for a way to subscribe to the src (url) change from an IFrame inside an Angular 7 Application. Is there a way to intercept the src Change?

like image 679
Sebastian Mehler Avatar asked Oct 25 '25 00:10

Sebastian Mehler


2 Answers

Actually it's simpler than you think, and you don't even need fromEvent and rxjs. Just listen to the load event like this:

<iframe [src]="src" (load)="test()"></iframe>

This is a working Stackblitz

And if you want the iframe reference you can easily get it also without ViewChild:

<iframe #frame [src]="src" (load)="test(frame)"></iframe>
like image 163
Federico Galfione Avatar answered Oct 27 '25 15:10

Federico Galfione


You can use the RxJS fromEvent constructor to take the 'load' event from the iFrame and subscribe to its changes. You can use the RxJS skip operator to ignore the initial load event if you need to.

Here's the gist of what you can do, but I've linked a full stackblitz example at the bottom of the answer too.

@ViewChild('iframe') iframe: ElementRef;

ngAfterViewInit(): void {
    fromEvent(this.iframe.nativeElement, 'load')
      // Skip the initial load event and only capture subsequent events.
      .pipe(skip(1))
      .subscribe((event: Event) => console.log(event.target));
}

Skip Docs: https://www.learnrxjs.io/operators/filtering/skip.html

From Event Docs: https://www.learnrxjs.io/operators/creation/fromevent.html

Full StackBlitz Example: https://stackblitz.com/edit/angular-dxmbgp

like image 45
Zailef Avatar answered Oct 27 '25 15:10

Zailef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!