能力中的概念
用户激活与它门控的那些 API
发布于 更新于
用户激活是窗口记录的交互状态,用来限制弹窗、手机振动等 API,防止脚本擅自调用。HTML 标准要求这些 API 只能在「only when the user is actively interacting with the web page or has interacted with the page at least once」的条件下使用。标准定义了粘性激活、瞬时激活与 history-action 激活;瞬时激活会在用户代理定义的时长之后过期。
工作原理
链接到“工作原理”一节HTML 标准用 last activation timestamp 跟踪近期激活,并用单独的布尔值记录历史粘性激活。
HTML 标准里的数据模型
链接到“HTML 标准里的数据模型”一节每个 Window 都带一个 last activation timestamp,它「either a DOMHighResTimeStamp, positive infinity (indicating that W has never been activated), or negative infinity (indicating that the activation has been consumed)」,初值为正无穷。它还分别带有 has sticky activation 与 has history-action activation 两个布尔值,两者初值都是 false。用户代理还定义了 transient activation duration,即「a constant number indicating how long a user activation is available for certain user activation-gated APIs」,规范预期它最多只有几秒,「so that the user can possibly perceive the link between an interaction with the page and the page calling the activation-gated API」(HTML Standard: Tracking user activation,html.spec.whatwg.org)。
粘性激活是窗口的 has sticky activation 布尔值,它「starts false, then changes to true (and never changes back to false) when W gets the very first activation notification」。当前高精度时间大于或等于 last activation timestamp,且小于该时间戳加 transient activation duration 时,瞬时激活成立,而这一状态「considered expired if it becomes false because the transient activation duration time has elapsed since the last user activation」。它也可能在到期之前就因为一次激活消耗而变为 false。
哪些事件会授予激活
链接到“哪些事件会授予激活”一节activation triggering input event 指 isTrusted 为 true 且类型为下列之一的事件:keydown,前提是该键既不是 Esc 键也不是用户代理保留的快捷键;mousedown;pointerdown,前提是事件的 pointerType 为 mouse;pointerup,前提是事件的 pointerType 不为 mouse;或 touchend。MDN 的清单补充说,被排除的按键「may vary by browser」,并点出 Caps Lock、Num Lock 与 Print Screen 在某些键盘上不产生用户激活(User activation,developer.mozilla.org)。
通知与消耗覆盖的浏览上下文集合并不相同,规范说明:「an activation consumption changes (to false) the transient activation states for all browsing contexts in the page, but an activation notification changes (to true) the states for a subset of those browsing contexts」,因为对全部上下文消耗激活的做法「prevents malicious sites from making multiple calls to an activation consuming API from a single user activation (possibly by exploiting a deep hierarchy of iframes)」。
四个门控级别
链接到“四个门控级别”一节规范把依赖激活的 API 分成四个级别。粘性激活门控的 API 需要粘性激活,「so they are blocked until the very first user activation」。瞬时激活门控的 API 需要瞬时激活但不消耗它,「so multiple calls are allowed per user activation until the transient state expires」。瞬时激活消耗型 API 需要瞬时激活,并在每次调用时消耗它。history-action 激活消耗型 API 需要 history-action 激活状态并在每次调用时消耗它,而且不同于瞬时激活,「there is no time limit within which such APIs must be used」。
UserActivation 接口的浏览器支持
链接到“UserActivation 接口的浏览器支持”一节BCD api.UserActivation 记录的支持起点为 Chrome 72、Firefox 120 与 Safari 16.4,并镜像到该记录列出的 Chromium 系浏览器(Edge、Opera、Samsung Internet 与 WebView),以及 Chrome Android、Firefox Android 与 iOS 上的 Safari(api/UserActivation.json,github.com)。hasBeenActive 与 isActive 两个成员适用同一组版本。
哪些 API 需要哪种状态
链接到“哪些 API 需要哪种状态”一节MDN 注明,这两份 API 清单都不完整。它列为需要瞬时激活的 API 包括 Navigator.share()、Window.open()、PaymentRequest.show()、Element.requestFullscreen()、MediaDevices.getDisplayMedia()、Document.requestStorageAccess()、Clipboard.read()、Clipboard.write()、USB.requestDevice()、Serial.requestPort()、HID.requestDevice()、Window.showOpenFilePicker()、Window.showSaveFilePicker()、Window.showDirectoryPicker()、EyeDropper.open()、Clients.openWindow() 与 WindowClient.focus()。它列为需要粘性激活的 API 包括 beforeunload 事件、Navigator.vibrate()、VirtualKeyboard.show()、Media 与 Web Audio API 的自动播放(尤其是 AudioContext),以及 clipboardchange 事件,MDN 指出后者也可以通过用户授予 clipboard-read 权限来启用。
瞬时门控的调用可在瞬时激活仍有效时运行,直到其持续时间结束,或某个消耗型 API 为页面中的全部浏览上下文消耗它。
浏览器提供 navigator.userActivation 时,可以读取粘性和瞬时激活状态。
读取两种激活状态
链接到“读取两种激活状态”一节navigator.userActivation 暴露 hasBeenActive,它「indicates whether the window has sticky user activation」,以及 isActive,它「indicates whether the window has transient user activation」(UserActivation,developer.mozilla.org)。各引擎开始支持这个接口的版本不同,读取前需要先检测。
function activationState() { if (!('userActivation' in navigator)) { // 接口不存在:改为依据触发的那个事件分支,而不是窗口状态。 return { hasBeenActive: null, isActive: null, readable: false }; } const { hasBeenActive, isActive } = navigator.userActivation; return { hasBeenActive, isActive, readable: true };}结果为 readable: false 时,在预期激活仍有效的时段调用 API,并处理激活失效导致的拒绝。click 本身不会触发激活;activation triggering input event 包括 keydown、mousedown、带条件的 pointerdown/pointerup 这一对,以及 touchend。受信任的 click 通常紧随其中之一发生,因此可以在它的处理器里调用 API,但仍需处理拒绝。
选择器或全屏请求被拦截后的回退
链接到“选择器或全屏请求被拦截后的回退”一节HTML 标准规定,缺少瞬时激活时,HTMLInputElement.showPicker() 抛出 NotAllowedError。Fullscreen 标准允许 requestFullscreen() 使用瞬时激活或用户触发的屏幕方向变化;请求通过检查后会消耗激活,全屏条件不成立时,返回的 Promise 以 TypeError 拒绝(HTMLInputElement.showPicker(),html.spec.whatwg.org;Element.requestFullscreen(),fullscreen.spec.whatwg.org)。
把两次调用直接放在各自的按钮处理器中。程序化请求失败时,下面的示例会显示规范定义的异常名称,同时保留原生日期输入框和行内内容。
<label>出发日期 <input id="departure" type="date"></label><button id="pick" type="button">选择日期</button><section id="preview"><h4>预览</h4><p>这段内容在行内也能使用。</p></section><button id="fullscreen" type="button">进入全屏</button><output id="status" aria-live="polite"></output><script> const departure = document.querySelector('#departure'); const preview = document.querySelector('#preview'); const status = document.querySelector('#status');
document.querySelector('#pick').addEventListener('click', () => { if (!('showPicker' in HTMLInputElement.prototype)) { status.value = '请直接使用日期输入框。'; departure.focus(); return; } try { departure.showPicker(); } catch (error) { status.value = `${error.name}:请直接使用日期输入框。`; departure.focus(); } });
document.querySelector('#fullscreen').addEventListener('click', async () => { if (!preview.requestFullscreen) { status.value = '不支持全屏,请使用行内内容。'; return; } try { await preview.requestFullscreen(); } catch (error) { status.value = `${error.name}:请使用行内内容。`; } });</script>如果 showPicker() 抛出 NotAllowedError,先确认调用仍发生在输入事件处理器中。若把它移入定时器,或等一段异步工作结束后才调用,用户代理定义的瞬时激活时长可能已经到期。
在激活仍有效时调用消耗型 API
链接到“在激活仍有效时调用消耗型 API”一节Web Share 属于瞬时激活消耗型 API,所以调用 share() 时必须仍有瞬时激活。异步步骤只有在调用前使激活过期,或让另一个 API 先消耗激活时,才会造成问题。
shareButton.addEventListener('click', async () => { if (!('share' in navigator)) { showCopyLinkDialog(); return; } const payload = { title: document.title, url: location.href }; try { await navigator.share(payload); } catch (error) { // 激活缺失或已被消耗时是 NotAllowedError;用户关掉分享面板也会 reject。 // 两者都不是需要往外抛的缺陷。 if (error.name === 'NotAllowedError') showCopyLinkDialog(); }});用手头已有的值构造 payload,可以在点击之后迅速调用 share(),catch 则处理激活已经失效导致的拒绝。一次 await 结束时激活仍可能有效,但瞬时持续时间也可能在等待期间结束;另一个消耗型 API 也可能先消耗激活。
另请参阅
链接到“另请参阅”一节- HTML Standard: Tracking user activation(html.spec.whatwg.org)
- User activation(developer.mozilla.org)
- UserActivation(developer.mozilla.org)
- Web Share API(w3.org)
- Fullscreen API(fullscreen.spec.whatwg.org)
- Web Share API
- Async Clipboard API
- Document.requestStorageAccess()
- Web Share 兼容性数据
规范
| 规范 | 状态 |
|---|---|
| 无。 | |