Youtube播放器用户体验优化

优化拖动进度条后无法通过键盘调整音量

As of 2025-04-07. See the latest version.

// ==UserScript==
// @name         Youtube播放器用户体验优化
// @namespace    https://www.youtube.com/
// @version      1.1
// @description  优化拖动进度条后无法通过键盘调整音量
// @author       Maverick_Pi
// @match        https://www.youtube.com/*
// @icon         https://www.youtube.com/favicon.ico
// @grant        none
// @run-at       document-idle
// @license      MIT
// ==/UserScript==
(function () {
  'use strict'

  function enhancePlayerFocus () {
    const progressBar = document.querySelector('.ytp-progress-bar')
    const video = document.querySelector('video')
    if (!progressBar || !video) return

    const outOfFocus = e => {
      document.activeElement.blur()
      video.focus()
    }

    // Prevent adding duplicate listeners
    progressBar.removeEventListener('focus', outOfFocus)
    progressBar.addEventListener('focus', outOfFocus)
  }

  // First execution
  enhancePlayerFocus()

  // Listen to URL changes
  const lastUrl = location.href
  new MutationObserver(() => {
    const currentUrl = location.href
    if (currentUrl !== lastUrl) {
      lastUrl = currentUrl
      setTimeout(() => {
        enhancePlayerFocus()
      }, 1000)
    }
  }).observe(document.body, { childList: true, subtree: true })

  // Listen to DOM update
  new MutationObserver(() => {
    enhancePlayerFocus()
  }).observe(document.body, { childList: true, subtree: true })
})()