Last active
October 17, 2024 11:05
-
-
Save micdenny/db03a814eaf4cd8abf95f77885d9316f to your computer and use it in GitHub Desktop.
How to detect a click event on a cross domain iframe (iframe.tracker)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div> | |
<iframe appIframeTracker (iframeClick)="onIframeClick()" src="http://www.google.com"></iframe> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
Directive, | |
ElementRef, | |
OnInit, | |
Renderer2, | |
Input, | |
Output, | |
EventEmitter, | |
HostListener | |
} from '@angular/core'; | |
@Directive({ | |
selector: '[appIframeTracker]' | |
}) | |
export class IframeTrackerDirective implements OnInit { | |
private iframeMouseOver: boolean; | |
@Input() debug: boolean; | |
@Output() iframeClick = new EventEmitter<ElementRef>(); | |
constructor(private el: ElementRef, private renderer: Renderer2) {} | |
ngOnInit(): void { | |
this.renderer.listen(window, 'blur', () => this.onWindowBlur()); | |
} | |
@HostListener('mouseover') | |
private onIframeMouseOver() { | |
this.log('Iframe mouse over'); | |
this.iframeMouseOver = true; | |
this.resetFocusOnWindow(); | |
} | |
@HostListener('mouseout') | |
private onIframeMouseOut() { | |
this.log('Iframe mouse out'); | |
this.iframeMouseOver = false; | |
this.resetFocusOnWindow(); | |
} | |
private onWindowBlur() { | |
if (this.iframeMouseOver) { | |
this.log('WOW! Iframe click!!!'); | |
this.resetFocusOnWindow(); | |
this.iframeClick.emit(this.el); | |
} | |
} | |
private resetFocusOnWindow() { | |
setTimeout(() => { | |
this.log('reset focus to window'); | |
window.focus(); | |
}, 100); | |
} | |
private log(message: string) { | |
if (this.debug) { | |
console.log(message); | |
} | |
} | |
} |
But what if i need type something inside the iframe?? it's imposible because always lose the focus on the textarea inside the iframe. Am i right ??
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the swift reply.
I understand that i cannot intercept the interaction inside the iframe. That's also not what i need. All i need to know is that there is any interaction. Just like your script does. But i would also need it for touch devices and not only desktop. But nevermind. Maybe that is not the way to go for me.