I’m making a video player in an Electron/React app.
I want to exit fullscreen when the user presses ESC, but it seems that the ESC key is not triggering any event.
// Player.js
const Player = (props) => {
...
const handleFullscreen = () => {
screenfull.toggle(playerContainerRef.current)
}
const handleKeyDown = (e) => {
console.log(e.code)
}
return (
...
<div ref={playerContainerRef} onKeyDown={handleKeyDown} ...>
<div onDoubleClick={handleFullscreen} ...>
<video .../>
</div>
</div>
)
})
When not in fullscreen, handleKeyDown()
prints every key I press, including ESC. But once I toggled/untoggled fullscreen, ESC is not triggering anymore.
EDIT
This was my previous code:
// App.js
const handleKeyDown = (e) => {
e.preventDefault()
switch (e.code) {
case 'Space':
refs.playerRef.current?.play()
break
case 'ArrowLeft':
refs.playerRef.current?.seekBackward()
break
case 'ArrowRight':
refs.playerRef.current?.seekForward()
break
case 'NumpadAdd':
refs.playerRef.current?.increaseSpeed()
break
case 'NumpadSubtract':
refs.playerRef.current?.decreaseSpeed()
break
case 'Escape':
console.log('Pressed ESC')
break
default:
break
}
}
But as I said, any condition above is triggered if the app has not entered fullscreen yet. Once fullscreen has been toggled and untoggled, the ESC condition is not working anymore 🤨
2
Answers
@frOzie, I think, you might as well use the
document
object to listen for the keydown event globally, instead of relying on the keydown event of a specific element. I’d like to share my code.This code uses the
useEffect
hook to add a global event listener for the keydown event on thedocument
object.!—
Please, make sure you have the neccessary dependencies installed, including
screenfull
if you haven’t already:Hope this maybe helpful.
I suggest you to use
keydown
event on the window object instead of the document object. This approach sometimes helps in capturing certain key events more reliably.Hope this approach more helpful, @frOzie