Is there a way to catch a click on a link inside an iframe
?
<iframe *ngIf="currentFrameUrl" id="contentFrame" [src]="currentFrameUrl | safe"></iframe>
My iframe component contains just a simple code which subscribes to observable variables.
export class ContentFrameComponent implements OnInit {
currentFrameUrl: string;
currentMenuState: boolean;
@ViewChild('contentFrame') iframe: ElementRef;
constructor(private frameService: ContentFrameService) {
this.currentMenuState = true;
}
ngOnInit(): void {
this.frameService.providerCurrentUrl$.subscribe(data => this.currentFrameUrl = data);
this.frameService.providerMenuState$.subscribe(data => this.currentMenuState = data);
}
ngAfterViewInit() {
let doc = this.iframe.nativeElement.contentDocument ||this.iframe.nativeElement.contentWindow;
if (typeof doc.addEventListener !== undefined) {
console.log("inside if - addEventListener") // Is shown
doc.addEventListener("click", this.iframeClickHandler, false)
} else if (typeof doc.attachEvent !== undefined) {
console.log("inside if - attachEvent ") // Does not show
doc.attachEvent("onclick", this.iframeClickHandler)
}
}
iframeClickHandler(): void {
console.log("Click test") // Does not show
}
}
My goal is to to catch click event on iframe
link, stop its propagation and set the url of the iframe link using either router.navigate
or location.go
/location.replaceState
. Not sure yet which option is better.
I have no control over the pages loaded inside the iframe
. I only know, that the links should contains such url
that can be used with my dynamic routes.
use @HostListener('window:blur', ['$event']) decorator, method attached with this decorator trigger on IFrame click.
@HostListener('window:blur', ['$event'])
onWindowBlur(event: any): void {
console.log('iframe clicked');
}
Note: Also this will work for cross-domain operations.
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