When dealing with Web APIs, you come across this error:
API can only be initiated by a user gesture
Why does this error happen, and what exactly does it mean?
Why does this happen?
This error means that the API which you are trying to call cannot just be called in your code, it needs to be initiated by a user gesture.
Let’s use the Fullscreen API as an example. This Web API has a method Element.requestFullscreen()
which places the target element
and the entire browser’s web page into fullscreen mode.
Below is an example of calling requestFullscreen
as soon as the page loads:
window.addEventListener("DOMContentLoaded", (event) => {
document.body.requestFullscreen();
});
This code will not work, as the action is not initiated by a user gesture. This limitation is applied so that you cannot force a website to display in fullscreen mode — you can only enter fullscreen mode via a user gesture or action.
The primary reason behind this limitation is for security reasons — imagine if videos could automatically play without you choosing to play them, or malicious websites could take your entire screen as soon as you visit the webpage. Restricting these API methods to user gestures ensures that they are intended by the user.
What should I do instead?
To fix this type of error, the API method needs to be called in the event listener for a user action, such as a click
orkeydown
event.
Here’s an example where we are calling requestFullscreen
once a button is clicked to fix our error above:
window.addEventListener("DOMContentLoaded", (event) => {
const button = document.getElementById("btn");
button.addEventListener("click", () => {
document.body.requestFullscreen();
});
});
Valid user gestures include:
change
click
contextmenu
dblclick
mouseup
pointerup
reset
submit
touchend
Events such as mousemove
or mouseenter
are not valid user gestures.
Conclusion
In conclusion, for security reasons, browsers prevent certain scripts from running unless triggered by a user action. This applies to methods other than Fullscreen
as well, such as playing video or audio via HTMLMediaElement.play()
.
Hope this helped!