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?
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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With