From cdda4e3acc6b24dd6a535721699d99b84e68a2b5 Mon Sep 17 00:00:00 2001 From: Kabeer Jaffri Date: Tue, 6 Feb 2024 13:50:58 +0500 Subject: [PATCH] Added useIFrameFocus, allows users to check if an Iframe is focused (clicked) or blured --- index.js | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/index.js b/index.js index f6e4fe2..69e191b 100644 --- a/index.js +++ b/index.js @@ -1,5 +1,41 @@ import * as React from "react"; +function useIFrameFocus(id: string, onFocus: () => any, onBlur: () => any) { + let iframeClickedLast: boolean; + + function windowBlurred(e: Event) { + const el = document.activeElement as HTMLElement; + if (el?.getAttribute('id') === id) { + iframeClickedLast = true; + onFocus(); + } + } + + function windowFocussed(e: Event) { + if (iframeClickedLast) { + iframeClickedLast = false; + onBlur(); + } + } + + React.useEffect(() => { + window.addEventListener('focus', windowFocussed, true); + window.addEventListener('blur', windowBlurred, true); + + return () => { + window.removeEventListener('focus', windowFocussed, true); + window.removeEventListener('blur', windowBlurred, true); + }; + }, []); + + function destroy() { + window.removeEventListener('focus', windowFocussed, true); + window.removeEventListener('blur', windowBlurred, true); + } + return destroy; +} + + function isShallowEqual(object1, object2) { const keys1 = Object.keys(object1); const keys2 = Object.keys(object2);