Created
April 16, 2020 22:36
-
-
Save rjerue/a8d43015d4c291a3c7157699c629b15e to your computer and use it in GitHub Desktop.
Detect if iframe is clicked
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 React from 'react'; | |
interface IFrameProps { | |
url: string; | |
onClick?: () => void; | |
} | |
const IFrameComponent: React.FC<IFrameProps> = ({ url, onClick }) => { | |
const ref = React.useRef<HTMLIFrameElement | null>(null); | |
React.useEffect(() => { | |
const iframe = ref.current; | |
if (onClick && iframe !== null) { | |
const windowBlurred = () => { | |
let start = 0; | |
const iframeSelected: FrameRequestCallback = (time) => { | |
if (start === 0) { | |
start = time; | |
} | |
if (time - start >= 1000) { | |
return; | |
} else if (document.activeElement === iframe) { | |
onClick(); | |
iframe.blur(); | |
} else { | |
window.requestAnimationFrame(iframeSelected); | |
} | |
}; | |
window.requestAnimationFrame(iframeSelected); | |
}; | |
window.addEventListener('blur', windowBlurred); | |
return () => { | |
window.removeEventListener('blur', windowBlurred); | |
}; | |
} | |
}, [ref, onClick]); | |
return ( | |
<iframe | |
ref={ref} | |
src={url} | |
frameBorder="0" | |
scrolling="no" | |
/> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment