Reputation: 21
I'm working on an exam system. After entering full screen, it is forbidden to exit full screen. But it seems that it is impossible to disable the esc key to control the exit of full screen. What should I do, or should I monitor to exit the full screen state, and then automatically full screen? thank you very much.
Upvotes: 1
Views: 4270
Reputation: 382
I think you will find that it is not possible to do what you want with JavaScript in a modern web browser. Part of the Living Standard for the Fullscreen API, found at https://fullscreen.spec.whatwg.org/ (Section 4: UI) says:
"If the end user instructs the user agent to end a fullscreen session initiated via requestFullscreen(), fully exit fullscreen the top-level browsing context’s active document."
Having tested in both Chrome and Firefox, you will find that attempting to capture a keydown event on the Escape key is not even possible while the browser is in fullscreen mode. Part of the web standard is that the browser's UI should provide an obvious and visible method to exit fullscreen whenever they choose.
Here is a small script you can add to your head tags to see that it won't work:
<script>
window.onload = function() {
let startExam = document.createElement('button');
startExam.innerHTML = 'Start Exam';
document.querySelector('body').appendChild(startExam);
startExam.addEventListener('click', (e) => {
if (!document.fullscreenElement)
document.documentElement.requestFullscreen();
document.addEventListener('keydown', (e) => {
console.log(`key down: ${e.key}`);
if (e.key === 'Escape')
console.log('escape');
});
document.addEventListener('keyup', (e) => {
console.log(`key up: ${e.key}`);
if (e.key === 'Escape')
console.log('escape');
});
document.addEventListener('keypress', (e) => {
console.log(`key press: ${e.key}`);
if (e.key === 'Escape')
console.log('escape');
});
});
};
</script>
This will print to the console the value of the key in various key events but you will find that it will never catch the Escape key.
It is also not possible to monitor for a fullscreenchange event to detect when the user exited and then to automatically send them back to fullscreen, because the browser will block any request for fullscreen from events that are not generated by user input. The closest you can get is to try using a mousemove event on the document to launch it back into fullscreen after it has exited, but at least on Firefox this will not work as you want because the browser sometimes loses focus when exiting fullscreen and will not detect the mousemove event until the user clicks back on the document.
Upvotes: 1