如何(取消)关注 YouTube 的视频元素

How to (Un)Focus YouTube's Video Element

This question comes from me trying to develop a browser extension to enhance YouTube's keyboard navigation.

1。背景

通常,我完全不清楚网页是在 YouTube 的 video 播放器元素上还是焦点在页面主体上。如果焦点在 video 元素上,则方向键将控制视频;否则,如果焦点在页面主体本身,箭头键将控制滚动。

我想添加一个快捷方式来(取消)激活 video 元素上的焦点。我该怎么做?

2。我试过的

仅使用 document.querySelector('video').focus()document.activeElement.blur() 对我不起作用。也不是 document.activeElement.setAttribute('disabled', 'true')...

3。其他信息

理想情况下,因为在视觉上,用户通常不清楚焦点在哪里,我想稍后添加一些 CSS 边框装饰,但我认为一旦之前的挑战已经完成。

Quite frankly, why the hell doesn't YouTube have all this already? It seems lazy on their part...

1。一种可能的解决方案

尝试将焦点改为 div #movie_player 元素:

document.addEventListener('keydown', (evt) => {
  if (evt.key === 'v') {
    const player = document.querySelector('#movie_player');

    document.activeElement.id === 'movie_player'
      ? player.blur()
      : player.focus();

    console.log('Active Element:', document.activeElement);
  }
});

2。奖励:上述解决方案的 Dart 版本

或者,由于您一直在使用 Dart:

document.onKeyDown.listen((KeyboardEvent keyboardEvent) {
  switch (keyboardEvent.key) {
    case 'v':
      final Element player = document.querySelector('#movie_player');

      document.activeElement.id == 'movie_player' 
          ? player.blur() 
          : player.focus();

      print('Active Element: ${document.activeElement}');

      break;
  }
});