Re: [mediacapture-main] Why does `navigator.mediaDevices.enumerateDevices()` require that `Document` must have active keyboard focus? (#905)

Actually referencing a document off main-thread would be a potential security bug that should get caught in review, so this was more of a spec-writing bug I think (e.g. we didn't trip over this in Firefox).

We [wrote some Mozilla-specific tests last year](https://phabricator.services.mozilla.com/D127047), but once #752 is resolved, it might be possible to write a test that queues tasks to call `enumerateDevices` repeatedly until a [visibilitychange](https://html.spec.whatwg.org/multipage/indices.html#event-visibilitychange) caused by `window.open()`, then checks that all collected promises resolve within the test timespan. This should fail intermittently at least if there's a non-compliant browser.

> We are cautious to start relying on the above, just to realize that we'd then get a small % of users hanging the page loads on background in practice when they open a page and then immediately navigate away, if some browser is doing something else under the "as-if" rule.

"as-if" would in practice require an interpretation of the spec that puts this check *after* the actual (time-consuming) enumeration step, I think, which would be a clear violation. But more immediately, you're right since, as mentioned in https://github.com/w3c/mediacapture-main/issues/752#issuecomment-1293797299 Firefox right now also requires [system focus](https://html.spec.whatwg.org/multipage/interaction.html#tlbc-system-focus), which is hard to check for in JS. So for now I'd recommend:

```js
const wait = ms => new Promise(r => setTimeout(r, ms));

if (document.visibilityState == "visible") {
  await Promise.race([navigator.mediaDevices.enumerateDevices(), wait(2000)]);
}
```
Not to be taken literally on pageload though, since `await navigator.mediaDevices.enumerateDevices()` may take a second to complete, involving waiting on IPC from the browser's main process, so a simple `await` would be a missed opportunity to do other stuff in the meantime, if you're looking to speed up pageload.

-- 
GitHub Notification of comment by jan-ivar
Please view or discuss this issue at https://github.com/w3c/mediacapture-main/issues/905#issuecomment-1295281993 using your GitHub account


-- 
Sent via github-notify-ml as configured in https://github.com/w3c/github-notify-ml-config

Received on Friday, 28 October 2022 17:47:06 UTC