Skip to content

Instantly share code, notes, and snippets.

@jtomchak
Created June 9, 2021 00:58
Show Gist options
  • Save jtomchak/cdf2efbe9a9e1b088db8467e20407a62 to your computer and use it in GitHub Desktop.
Save jtomchak/cdf2efbe9a9e1b088db8467e20407a62 to your computer and use it in GitHub Desktop.
Getting event on Interaction with an Embedded iFrame
import React from 'react'
export function iFrame({props}){
const iframeRef = React.useRef(null);
useElementInteration({
elementRef: iframeRef,
onInteraction: () =>
console.log("Interaction of iframe!!!")
});
return (
<div ref={iframeRef}>
<iframe src={...} />
<div>
)
}
import React from 'react';
/**
* window on blur is triggered when the iframe window becomes focused
* using mouse over and out to know if that blur happens over the iframe or somewhere else.
* @param elementRef ref to element to track
* @param onInteraction function to invoke when interaction is triggered
*/
export function useElementInteration({ elementRef, onInteraction }) {
const [elementMouseOver, setElementOver] = React.useState(false);
const toogleElementMouseover = React.useCallback(() =>
setElementOver(!elementMouseOver),
);
React.useEffect(() => {
const element = elementRef.current;
if (!element) return null;
function captureEvent(e) {
if (!elementMouseOver) return null;
onInteraction();
}
window.addEventListener('blur', captureEvent);
element.addEventListener('mouseover', toogleElementMouseover);
element.addEventListener('mouseout', toogleElementMouseover);
function cleanup() {
element.removeEventListener('mouseover', toogleElementMouseover);
element.removeEventListener('mouseout', toogleElementMouseover);
window.removeEventListener('blur', captureEvent);
}
return cleanup;
}, [elementRef, onInteraction]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment