Skip to content

Instantly share code, notes, and snippets.

@rosko
Forked from tannerlinsley/onWindowFocus.ts
Created July 8, 2021 01:12
Show Gist options
  • Save rosko/3502361bcb36f0055b24b37b00ff0a49 to your computer and use it in GitHub Desktop.
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
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