Skip to content

Instantly share code, notes, and snippets.

@rjerue
Created April 16, 2020 22:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rjerue/a8d43015d4c291a3c7157699c629b15e to your computer and use it in GitHub Desktop.
Save rjerue/a8d43015d4c291a3c7157699c629b15e to your computer and use it in GitHub Desktop.
Detect if iframe is clicked
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