-
-
Save rosko/3502361bcb36f0055b24b37b00ff0a49 to your computer and use it in GitHub Desktop.
A utility function to detect window focusing without false positives from iframe focus events
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
const state = { | |
added: false, | |
interval: false, | |
inFrame: false, | |
callbacks: [] | |
} | |
export default function onWindowFocus(cb) { | |
state.callbacks.push(cb) | |
start() | |
return () => { | |
state.callbacks = state.callbacks.filter(d => d !== cb) | |
stop() | |
} | |
} | |
function start () { | |
if (state.interval) { | |
clearInterval(state.interval) | |
} | |
if (!state.added) { | |
state.added = true | |
window.addEventListener('focus', e => { | |
if (state.inFrame) { | |
state.inFrame = false | |
return | |
} else { | |
state.callbacks.forEach(cb => cb(e)) | |
} | |
}) | |
} | |
state.interval = setInterval(() => { | |
const iframes = [...document.getElementsByTagName('iframe')] | |
console.log('Polling iframes... found: ', iframes.length) | |
iframes.forEach(el => { | |
if (el.___onWindowFocusHandled) { | |
return | |
} | |
el.___onWindowFocusHandled = true | |
el.addEventListener('touchend', () => { | |
state.inFrame = true | |
}) | |
el.addEventListener('mouseup', () => { | |
state.inFrame = true | |
}) | |
el.addEventListener('focus', () => { | |
state.inFrame = true | |
}) | |
}) | |
}, 500) | |
} | |
function stop () { | |
if (!state.callbacks.length) { | |
clearInterval(state.interval) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment