From eb331def1045117530a58f2c87a2415afe016075 Mon Sep 17 00:00:00 2001 From: Zhenyu FU Date: Sun, 20 Oct 2024 21:38:43 +0800 Subject: [PATCH] Add Keyboard Lock API support (Chromium 68+ & HTTPS only) This enables web browser to capture key combos, e.g., Alt+F4, Alt+Tab, and send it to web page. Limitations: 1) Chromium 68+ only; 2) User should click full screen button inside the webpage. API won't work when toggling full screen via F11 or browser menu. 3) HTTPS instead of HTTP. - https://developer.chrome.com/docs/capabilities/web-apis/keyboard-lock - https://developer.mozilla.org/en-US/docs/Web/API/Navigator/keyboard --- app/ui.js | 11 ++++++++++- core/util/browser.js | 3 ++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/app/ui.js b/app/ui.js index d973ffd42..47960d7d3 100644 --- a/app/ui.js +++ b/app/ui.js @@ -29,7 +29,7 @@ import "core-js/stable"; import "regenerator-runtime/runtime"; import * as Log from '../core/util/logging.js'; import _, { l10n } from './localization.js'; -import { isTouchDevice, isSafari, hasScrollbarGutter, dragThreshold, supportsBinaryClipboard, isFirefox, isWindows, isIOS, supportsPointerLock } +import { isTouchDevice, isSafari, hasScrollbarGutter, dragThreshold, supportsBinaryClipboard, isFirefox, isWindows, isIOS, supportsPointerLock, supportsKeyboardLock } from '../core/util/browser.js'; import { setCapture, getPointerEvent } from '../core/util/events.js'; import KeyTable from "../core/input/keysym.js"; @@ -1841,6 +1841,9 @@ const UI = { document.mozFullScreenElement || // currently working methods document.webkitFullscreenElement || document.msFullscreenElement) { + if (supportsKeyboardLock) { + navigator.keyboard.unlock(); + } if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.mozCancelFullScreen) { @@ -1860,6 +1863,12 @@ const UI = { } else if (document.body.msRequestFullscreen) { document.body.msRequestFullscreen(); } + // No need to explicitly ask for permission, + // but it's expected that user grant it since Chromium 131. + // See https://developer.chrome.com/blog/keyboard-lock-pointer-lock-permission + if (supportsKeyboardLock) { + navigator.keyboard.lock(); + } } UI.updateFullscreenButton(); }, diff --git a/core/util/browser.js b/core/util/browser.js index 436738b96..a8b1bfef3 100644 --- a/core/util/browser.js +++ b/core/util/browser.js @@ -27,6 +27,8 @@ window.addEventListener('touchstart', function onFirstTouch() { // brings us a bit closer but is not optimal. export let dragThreshold = 10 * (window.devicePixelRatio || 1); +export const supportsKeyboardLock = ('keyboard' in navigator && 'lock' in navigator.keyboard && typeof(navigator.keyboard.lock) === 'function'); + let _supportsCursorURIs = false; try { @@ -174,4 +176,3 @@ export function supportsPointerLock() { if (isIOS() || isIE()) { return false; } return (document.exitPointerLock); } -