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);