requestFullscreen() not working with modifier keys inside keyup event

354 Views Asked by At

I want to toggle fullscreen on an element, but the requestFullscreen() function isn't working, despite the fact it is called while responding to user interaction (MDN). I can't find out why it doesn't work with Modifier Keys (MDN).

Here's the snippet from my fiddle:

document.addEventListener("keyup", (e) => {
  e.preventDefault();
  if (document.fullscreenElement)
    return document.exitFullscreen()
  document.body.firstElementChild.requestFullscreen();  // Fails on CTRL, SHIFT, ALT ...
});

I also don't understand how it does work if you press a mouse button or any other key press between each toggle with CTRL, SHIFT, or ALT keys. For example, this would work: Left Mouse Click, Shift, Shift, Left Mouse Click, Shift, Shift...

I need this to work for my Chrome Extension, so maybe there is a workaround? Thanks.

2

There are 2 best solutions below

0
On BEST ANSWER

Updated MDN docs - Features gated by user activation - specify exactly what activation triggering input events require. In short, the Esc key and shortcut keys reserved by the user agent (aka modifier keys) don't trigger transient activation. There is no workaround.

1
On

If I understood your explanation correctly, you mean that when you first interact with the element, for example, click on the element first and then press let's say enter, it works. But when you come for the first time and try to press any key, it does not enter the full screen.

In general, the keydown and keyup events can be fired without first clicking on an element. That means if you are triggering the full-screen mode on the keyup event then it should work without user interaction but it won't. The reason is-

The requestFullscreen() method needs that it is contacted in reaction to a user gesture, such as a click event, touch event, or keydown event that was triggered by a user interaction. This is a security feature of the browser to stop websites from taking over the user's screen without their consent.

When a user interacts with a webpage by clicking a button, tapping on the screen, or pressing a key, the browser believes that the user has initiated the action and accordingly allows the website to take over the screen using the requestFullscreen() method.

However, if the requestFullscreen() method is called from a keyup event that was not triggered by a user interaction, such as a script like a keypress a key press, the browser may not permit the website to take over the screen because it cannot decide whether the action was started by the user or by a script.

This is likely why the requestFullscreen() method fails when called from a keyup event that is not initiated by a user motion, such as when using modifier keys like CTRL, SHIFT, or ALT.