Created
June 9, 2021 00:58
-
-
Save jtomchak/cdf2efbe9a9e1b088db8467e20407a62 to your computer and use it in GitHub Desktop.
Getting event on Interaction with an Embedded iFrame
This file contains hidden or 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' | |
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> | |
) | |
} |
This file contains hidden or 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'; | |
/** | |
* 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